Java的IO操作都是基於流進行操作的,為了提高讀寫效率一般需要進行緩沖。
簡單的示例程序如下:
/**
* 讀出1.txt中的內容,寫入2.txt中
*
*/
import java.io.*;
public class ReadWriteFile{
public static void main(String[] args){
try{
File read = new File("c:\1.txt");
File write = new File("c:\2.txt");
BufferedReader br = new BufferedReader(
new FileReader(read));
BufferedWriter bw = new BufferedWriter(
new FileWriter(write));
String temp = null;
temp = br.readLine();
while(temp != null){
//寫文件
bw.write(temp + "
"); //只適用Windows系統
//繼續讀文件
temp = br.readLine();
}
bw.close();
br.close();
}catch(FileNotFoundException e){ //文件未找到
System.out.println (e);
}catch(IOException e){
System.out.println (e);
}
}
}