1 打开文件。
本例以FileInputStream的read(buffer)方法,每次从源程序文件OpenFile.java中读取512个字节,存储在缓冲区 buffer中,再将以buffer中的值构造的字符串new String(buffer)显示在屏幕上。程序如下:

import java.io.*; 

public class OpenFile 

{ 

 public static void main(String args[]) throws IOException 

 { 

 try 

 { //创建文件输入流对象 

 FileInputStream rf = new FileInputStream( "OpenFile.java "); 

 int n=512; 

 byte buffer[] = new byte[n]; 

 while ((rf.read(buffer,0,n)!=-1) && (n> 0)) //读取输入流 

 { 

 System.out.print(new String(buffer)); 

 } 

 System.out.println(); 

 rf.close(); //关闭输入流 

 } 

 catch (IOException ioe) 

 { 

 System.out.println(ioe); 

 } 

 catch (Exception e) 

 { 

 System.out.println(e); 

 } 

 } 

}


例 2 写入文件。
本例用System.in.read(buffer)从键盘输入一行字符,存储在缓冲区buffer中,再以FileOutStream的write(buffer)方法,将buffer中内容写入文件Write1.txt中,程序如下:

import java.io.*; 

public class Write1 

{ 

 public static void main(String args[]) 

 { 

 try 

 { 

 System.out.print( "Input: "); 

 int count,n=512; 

 byte buffer[] = new byte[n]; 

 count = System.in.read(buffer); //读取标准输入流 

 FileOutputStream wf = new FileOutputStream( "Write1.txt "); 

 //创建文件输出流对象 

 wf.write(buffer,0,count); //写入输出流 

 wf.close(); //关闭输出流 

 System.out.println( "Save to Write1.txt! "); 

 } 

 catch (IOException ioe) 

 { 

 System.out.println(ioe); 

 } 

 catch (Exception e) 

 { 

 System.out.println(e); 

 } 

 } 

}