日期:2014-05-20 浏览次数:20862 次
用不同形式的流完成对文件的拷贝
单纯的字符流:
FileCopy .java
packagefilewriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileCopy { publicstatic void main(String[] args) { FileReaderfr = null; FileWriterfw = null; try{ fr = new FileReader(newFile("src/FileWriter/FileCopy.java")); fw= new FileWriter(new File("D:/filecopy.txt")); charbuf [] = new char [1024]; intlen = 0; while((len = fr.read(buf))!=-1){ fw.write(buf,0, len); } }catch (Exception e) { //TODO Auto-generated catch block e.printStackTrace(); }finally{ if(fr!= null){ try{ fr.close(); }catch (IOException e) { //TODO Auto-generated catch block e.printStackTrace(); } } } if(fw!= null){ try{ fw.close(); }catch (IOException e) { //TODO Auto-generated catch block e.printStackTrace(); } } } }
带缓冲的字符流:
BufferedFileCopy.java
package bufferedstream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class BufferedFileCopy { publicstatic void main(String[] args) throws IOException { FileReaderfr = new FileReader(new File("D:/buffered.txt")); FileWriter fw = new FileWriter(new File("buf.txt")); java.io.BufferedReader br = new BufferedReader(fr); java.io.BufferedWriter bw = new BufferedWriter(fw); String content = null; while ((content = br.readLine())!= null) { bw.write(content); bw.newLine(); bw.flush(); } bw.close(); br.close(); } }