1、Java语言打开文件
本例以FileInputStream的read(buffer)方法,每次从源程序文件OpenFile.java中读取512个字节,存储在缓冲区buffer中,再将以buffer中的值构造的字符串newString(buffer)显示在屏幕上。程序如下:
- importjava.io.*;
- publicclassOpenFile
- {
- publicstaticvoidmain(Stringargs[])throwsIOException
- {
- try
- {//创建文件输入流对象
- FileInputStreamrf=newFileInputStream("OpenFile.java");
- intn=512;
- bytebuffer[]=newbyte[n];
- while((rf.read(buffer,0,n)!=-1)&&(n>0))//读取输入流
- {
- System.out.print(newString(buffer));
- }
- System.out.println();
- rf.close();//关闭输入流
- }
- catch(IOExceptionioe)
- {
- System.out.println(ioe);
- }
- catch(Exceptione)
- {
- System.out.println(e);
- }
- }
- }
例2Java语言写入文件
本例用System.in.read(buffer)从键盘输入一行字符,存储在缓冲区buffer中,再以FileOutStream的write(buffer)方法,将buffer中内容写入文件Write1.txt中,程序如下:
- importjava.io.*;
- publicclassWrite1
- {
- publicstaticvoidmain(Stringargs[])
- {
- try
- {
- System.out.print("Input:");
- intcount,n=512;
- bytebuffer[]=newbyte[n];
- count=System.in.read(buffer);//读取标准输入流
- FileOutputStreamwf=newFileOutputStream("Write1.txt");
- //创建文件输出流对象
- wf.write(buffer,0,count);//写入输出流
- wf.close();//关闭输出流
- System.out.println("SavetoWrite1.txt!");
- }
- catch(IOExceptionioe)
- {
- System.out.println(ioe);
- }
- catch(Exceptione)
- {
- System.out.println(e);
- }
- }
- }
【编辑推荐】