JAVA_五種方法復(fù)制一個文本文件

public class TestTransStream1 {

/**

  • 需求:復(fù)制一個文本文件。

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

//字節(jié)流+字符流緩沖區(qū)方式
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();
}

//字節(jié)流+字節(jié)流緩沖區(qū)方式
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();

}

// 字節(jié)流方式 也適用于非文本文件
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();

}

//字符流加緩沖區(qū)方式
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();
}
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容