IO字符流五种方式复制文件
1 package com.qyh.io; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileReader; 6 import java.io.FileWriter; 7 import java.io.IOException; 8 9 /* 10 * 字符流复制文本文件 11 * 12 * 13 */ 14 15 public class CopyTextDemo { 16 public static void main(String[] args) throws IOException { 17 method1("a.txt", "b.txt"); 18 method2("a.txt", "c.txt"); 19 method3("a.txt", "d.txt"); 20 method4("a.txt", "e.txt"); 21 method5("a.txt", "f.txt"); 22 } 23 24 //高效字符流一次读取一行 25 private static void method5(String srcString, String destString) throws IOException { 26 BufferedReader br = new BufferedReader(new FileReader(srcString)); 27 BufferedWriter bw = new BufferedWriter(new FileWriter(destString)); 28 29 String line = null; 30 while((line=br.readLine())!=null) { 31 bw.write(line); 32 bw.newLine(); 33 bw.flush(); 34 } 35 bw.close(); 36 br.close(); 37 38 } 39 40 // 高效字符流一次读取一个字符数组 41 private static void method4(String srcString, String destString) throws IOException { 42 BufferedReader br = new BufferedReader(new FileReader(srcString)); 43 BufferedWriter bw = new BufferedWriter(new FileWriter(destString)); 44 45 char[] ch = new char[1024]; 46 int len = 0; 47 while ((len = br.read(ch)) != -1) { 48 bw.write(ch, 0, len); 49 bw.flush(); 50 } 51 bw.close(); 52 br.close(); 53 54 } 55 56 // 高效字符流一次读一个字符 57 private static void method3(String srcString, String destString) throws IOException { 58 BufferedReader br = new BufferedReader(new FileReader(srcString)); 59 BufferedWriter bw = new BufferedWriter(new FileWriter(destString)); 60 61 int ch = 0; 62 while ((ch = br.read()) != -1) { 63 bw.write(ch); 64 } 65 bw.close(); 66 br.close(); 67 68 } 69 70 // 一次读取一个字符数组 71 private static void method2(String srcString, String destString) throws IOException { 72 FileReader fr = new FileReader(srcString); 73 FileWriter fw = new FileWriter(destString); 74 75 char[] ch = new char[1024]; 76 int len = 0; 77 while ((len = fr.read(ch)) != -1) { 78 fw.write(ch, 0, len); 79 fw.flush(); 80 } 81 fw.close(); 82 fr.close(); 83 84 } 85 86 // 一次读取一个字符 87 private static void method1(String srcString, String destString) throws IOException { 88 // 封装数据源 89 FileReader fr = new FileReader(srcString); 90 // 封装目的地 91 FileWriter fw = new FileWriter(destString); 92 // 读写数据 93 int ch = 0; 94 while ((ch = fr.read()) != -1) { 95 fw.write(ch); 96 } 97 // 释放资源 98 fw.close(); 99 fr.close(); 100 101 } 102 103 }
我亦无他,惟手熟尔