使用缓冲读写
import java.io.*; class BufferIo { public static void main(String[] args) throws IOException { FileWriter fw = new FileWriter("demoBuffer.txt"); BufferedWriter bfw = new BufferedWriter(fw); for(int x=0;x<5;x++) { bfw.write("abc"+x); bfw.newLine(); bfw.flush(); } bfw.close(); bufferRead(); } public static void bufferRead() throws IOException { FileReader fr = new FileReader("demoBuffer.txt"); BufferedReader br = new BufferedReader(fr); String str = ""; while((str = br.readLine())!=null){ //读一行,如果不存在则返回null System.out.println(str); } br.close(); //只需关闭缓冲区 } }
import java.io.*; class CopyBuffer { public static void main(String[] args) { BufferedReader br = null; BufferedWriter bw = null; try{ br = new BufferedReader(new FileReader("bufferIo.java")); bw = new BufferedWriter(new FileWriter("copy_bufferIo.txt")); String line = null; while((line = br.readLine()) != null){ bw.write(line); bw.newLine(); bw.flush(); } }catch(IOException e){ throw new RuntimeException("读写失败"); }finally{ try{ if(br != null){ br.close(); } }catch(IOException e){ throw new RuntimeException("关闭读流失败"); } try{ if(bw != null){ bw.close(); } }catch(IOException e){ throw new RuntimeException("关闭写流失败"); } } } }