复制文本文件 5中方式
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class CopyFileDemo { public static void main(String[] args) throws IOException { String scrString = "a.txt"; String destString = "b.txt"; method1(scrString,destString); method2(scrString,destString); method3(scrString,destString); method4(scrString,destString); method5(scrString,destString); } //基本字符一次读写一个字符 private static void method1(String scrString,String destString) throws IOException{ FileReader fr = new FileReader(scrString); FileWriter fw = new FileWriter(destString); int ch = 0; while((ch = fr.read()) != -1){ fw.write(ch); } fw.close(); fr.close(); } //基本字符流,一次写一个数组 private static void method2(String scrString,String destString) throws IOException{ FileReader fr = new FileReader(scrString); FileWriter fw = new FileWriter(destString); char[] chs = new char[1024]; int len = 0; while((len = fr.read(chs))!=-1){ fw.write(chs, 0, len); } fw.close(); fr.close(); } //字符缓冲流一次读写一个字符 private static void method3(String scrString,String destString) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(scrString)); BufferedWriter bw = new BufferedWriter(new FileWriter(destString)); int ch = 0; while((ch = br.read())!=-1){ bw.write(ch); } bw.close(); br.close(); } //字符缓冲流 一次读写一个字符数组 private static void method4(String scrString,String destString) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(scrString)); BufferedWriter bw = new BufferedWriter(new FileWriter(destString)); char[] chs = new char[1024]; int len = 0; while((len = br.read(chs)) != -1){ bw.write(chs, 0, len); } bw.close(); br.close(); } //字符缓冲流一次写一个字符串 private static void method5(String scrString,String destString) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(scrString)); BufferedWriter bw = new BufferedWriter(new FileWriter(destString)); String line = null; while((line = br.readLine()) != null){ bw.write(line); bw.newLine(); bw.flush(); } bw.close(); br.close(); }}