复制文本文件字符流的5种方式

时间:2021-06-19 21:03:39
package cn.itcast_01;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


/*
 * 文本复制
 * 数据源
 * a.txt
 * 目的地
 * b.txt
 */
public class CopyFileDemo1 {
public static void main(String[] args) throws IOException {
String str1="a.txt";
String str2="b.txt";
//method1(str1,str2);
//method2(str1,str2);
//method3(str1,str2);
//method4(str1,str2);
method5(str1,str2);
}
//字符缓冲流一次读取一个字符串
private static void method5(String str1, String str2) throws IOException {
BufferedReader br=new BufferedReader(new FileReader(str1));
BufferedWriter bw=new BufferedWriter(new FileWriter(str2));
String line=null;
while((line=br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
br.close();
bw.close();
}
//字符缓冲流一次读取一个字符数组
private static void method4(String str1, String str2) throws IOException {
BufferedReader br=new BufferedReader(new FileReader(str1));
BufferedWriter bw=new BufferedWriter(new FileWriter(str2));
char []c=new char[1024];
int len=0;
while((len=br.read(c))!=-1){
bw.write(c,0,len);
}
br.close();
bw.close();

}
//字符缓冲流一次读取一个字符
private static void method3(String str1, String str2) throws IOException {
BufferedReader br=new BufferedReader(new FileReader(str1));
BufferedWriter bw=new BufferedWriter(new FileWriter(str2));
int by=0;
while((by=br.read())!=-1){
bw.write(by);
}
br.close();
bw.close();
}
//基本字符流一次读取一个字符数组
private static void method2(String str1, String str2) throws IOException {
FileReader fr=new FileReader(str1);
FileWriter fw=new FileWriter(str2);
char[]c=new char[1024];
int l=0;
while((l=fr.read(c))!=-1){
fw.write(c, 0, l);
}
fr.close();
fw.close();
}
//基本字符流一次读取一个字符
private static void method1(String str1, String str2) throws IOException{//数据源:str1   目的地:str2
FileReader fr=new FileReader(str1);
FileWriter fw=new FileWriter(str2);
int by=0;
while((by=fr.read())!=-1){
fw.write(by);
}
fr.close();
fw.close();

}


}