Java 的文件(读 写)输入输出(转)
1、流: 它是通过缓冲机制将数据从生产者(如键盘、磁盘文件、内存或其他设备)传送到接受该数据的消费者(如屏幕、文件或者内存等)的这一过程的抽象。 2、有关的Java包: Java.io包中包括许多类提供许多有关文件的各个方面操作。 3、有关文件名及目录名的类:File 类独立于系统平台,利用构造函数 File( String path)、 File(String path, String FileName)、 File(File dir, String name) 等创建出File 对象;再利用canRead() 、canWrite()、 getParent()、 getPath()等成员函数实现对文件的各个属性的操作。 import java.io.*; public class FileTest { public static void main(String []args) { String FileName="C:\\temp\\myfile.dat" File myFile=new File(FileName); If( ! myFile. exists() ) { System.err.println("Can't Find " + FileName); return; } System.out.println("File " + FileName + "is " +myFile.length() + "bytes Long !"); If( myFile. isDirectory() ) { System.err.println("File" + FileName +"Is a Directory !"); return; } } } 4、有关文件内容(数据)操作的类: 4.1 输入输出抽象基类InputStream/OutputStream ,实现文件内容操作的基本功能函数read()、 write()、close()、skip()等;一般都是创建出其派生类对象(完成指定的特殊功能)来实现文件读写。在文件读写的编程过程中主要应该注意异常处理的技术。 4.2 FileInputStream/FileOutputStream: 用于本地文件读写(二进制格式读写并且是顺序读写,读和写要分别创建出不同的文件流对象); 本地文件读写编程的基本过程为: ① 生成文件流对象(对文件读操作时应该为FileInputStream类,而文件写应该为FileOutputStream类); ② 调用FileInputStream或FileOutputStream类中的功能函数如read()、write(int b)等)读写文件内容; ③ 关闭文件(close())。 4.3 PipedInputStream/PipedOutputStream: 用于管道输入输出(将一个程序或一个线程的输出结果直接连接到另一个程序或一个线程的输入端口,实现两者数据直接传送。操作时需要连结); 4.3.1 管道的连接: 方法之一是通过构造函数直接将某一个程序的输出作为另一个程序的输入,在定义对象时指明目标管道对象 PipedInputStream pInput=new PipedInputStream(); PipedOutputStream pOutput= new PipedOutputStream(pInput); 方法之二是利用双方类中的任一个成员函数 connect()相连接 PipedInputStream pInput=new PipedInputStream(); PipedOutputStream pOutput= new PipedOutputStream(); pinput.connect(pOutput); 4.3.2 管道的输入与输出: 输出管道对象调用write()成员函数输出数据(即向管道的输入端发送数据);而输入管道对象调用read()成员函数可以读起数据(即从输出管道中获得数据)。这主要是借助系统所提供的缓冲机制来实现的。 4.4、随机文件读写: RandomAccessFile类(它直接继承于Object类而非InputStream/OutputStream类),从而可以实现读写文件中任何位置中的数据(只需要改变文件的读写位置的指针)。 随机文件读写编程的基本过程为: ① 生成流对象并且指明读写类型; ② 移动读写位置; ③ 读写文件内容; ④ 关闭文件。 StringBuffer buf=new StringBuffer(); char ch; while( (ch=(char)System.in.read()) !='\n') { buf.append( ch); } //读写方式可以为"r" or "rw" RandomAccessFile myFileStream=new RandomAccessFile("myFile.dat"," rw"); myFileStream . seek(myFileStream.length()) ; myFileStream.writeBytes(buf.toString()); //将用户从键盘输入的内容添加到文件的尾部 myFileStream.close(); 4.5 DataInput/DataOutput接口:实现与机器无关的各种数据格式读写(如readChar() 、readInt()、readLong()、readFloat(),而readLine()将返回一个String)。其中RandomAccessFile类实现了该接口,具有比FileInputStream或FileOutputStream类更灵活的数据读写方式。 4.6 标准输入输出流:System.in(如:char c=System.in.read())和System.out(如:System.out.println()、System.out.println())。 try { char ch=System.in.read(); //返回二进制数据(低8位为键盘的ASCII码) } catch(IOException e) { } 4.7、文件操作的一般方法: (1)生成一个输入输出文件类的对象(根据所要操作的类型); (2)调用此类的成员函数实现文件数据内容的读写; (3)关闭此文件。 
|