PrintWriter和PrintStream用法

簡介

PrintWriter和PrintStream是兩個打印流,當我們需要對數據進行輸出時,一般用的會比較多。比如說Socket通信,數據通過Socket流入流出,在流出的時候可能會用到PrintWriter。在選擇這兩個流的時候,如果需要對字符操作用PrintWriter,字節操作則用PrintStream。

使用

當我們用PrintWriter時,需要指定文件名,或者自定義一個字節輸出流或字符輸出流。

通過PrintStream改變System.out.Println()的輸出方向

 System.setOut(new PrintStream(new FileOutputStream("print.txt")));

 System.out.println("哈哈哈啊哈");

System.setOut()可以改變我們的輸出方向,加上 PrintStream可以指定輸出位置,當我們輸出的時候,“哈哈哈啊哈”不會在控制檯顯示,直接輸入到print.txt文件中。

PrintStream實現文件的拷貝

package Print;

import java.io.*;

public class PrintStream_Copy {
    public static void main(String[] args) throws IOException {
        File file=new File("16流");

        BufferedInputStream br=new BufferedInputStream(new FileInputStream(file));

        PrintStream ps=new PrintStream(new FileOutputStream("src\\"+file.getName()),true);//true表示自動刷新

        int temp=0;
        while ((temp=br.read())!=-1){
            ps.print((char) temp);
        }
        br.close();
        ps.close();
        System.out.println("拷貝成功!");
    }
}

文件拷貝成功,但文件夾裏面的中文字符會亂碼。原因我們之前提到過,請看: FileOutputStream寫入中文字符後,然後用FileInputStream一個個讀取,出現的亂碼問題 

PrintWriter實現文件的拷貝

package Print;

import java.io.*;

public class PrintWriter_Copy {
    public static void main(String[] args) throws IOException {
        File file=new File("16流");

        BufferedReader br=new BufferedReader(new FileReader(file));

        PrintWriter pw=new PrintWriter(new FileWriter("src\\"+file.getName()),true);//爲true:println,printf或format方法將刷新輸出緩衝區

        String temp=null;

        while ((temp=br.readLine())!=null){
            pw.println(temp);  //每次將一行數據輸入到目標位置,並且 刷新流
//            pw.write(temp);  //不換行  連在一起   
        }
        br.close();
        pw.close();
        System.out.println("Copy成功!");
    }
}

總結:

對於這兩個打印流而言,個人感覺PrintWriter用的會比較多。當然用的時候還是的根據需求來。


      每日雞湯: 沒有壓力的生活,並不是所謂的享福,而是慢性折磨。


Over!

發佈了33 篇原創文章 · 獲贊 41 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章