JAVA_五种方法复制一个文本文件

public class TestTransStream1 {

/**

  • 需求:复制一个文本文件。

**/
public static void main(String[] args) throws IOException {
test5();
// test4();
// test3();
// test2();
// test1();
}

//字节流+字符流缓冲区方式
private static void test5() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt")));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("b.txt")));
String temp;

 while ((temp=br.readLine())!=null)
 {
     bw.write(temp);
     bw.newLine();
 }
 br.close();
 bw.close();
}

//字节流+字节流缓冲区方式
private static void test4() throws IOException{
 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.txt"));
 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("b.txt"));

 int ch;
 while ((ch=bis.read())!=-1)
 {
     bos.write(ch);
 }
 bis.close();
 bos.close();

}

// 字节流方式 也适用于非文本文件
private static void test3() throws IOException {
FileInputStream in = new FileInputStream("a.txt");
FileOutputStream fo = new FileOutputStream("b.txt");
int ch;
while((ch=in.read())!=-1)
{
    fo.write(ch);
}
in.close();
fo.close();

}

//字符流加缓冲区方式
private static void test2() throws IOException {
BufferedReader br= new BufferedReader(new FileReader("a.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));
String temp;
while ((temp=br.readLine())!=null)
{
bw.write(temp);
bw.newLine();
temp = br.readLine();
}
br.close();
bw.close();

}

//字符流方式
private static void test1() throws IOException {
FileReader fr = new FileReader("a.txt");
FileWriter fw = new FileWriter("b.txt");
int ch=fr.read();
while (ch!=-1)
{
fw.write(ch);
ch=fr.read();
}
fr.close();
fw.close();
}
}

你可能感兴趣的:(JAVA_五种方法复制一个文本文件)