天天看點

使用列印流優化資料輸出 | 帶你學《Java語言進階特性》之六十五

上一篇:“有限”的OutputStream | 帶你學《Java語言進階特性》之六十四

為了彌補原始的OutputStream功能的不足,java.io包為開發者提供了列印流:PrintStream類和PrintWriter類,本節将為讀者介紹其基本内容和使用方法。

【本節目标】

通過閱讀本節内容,你将了解到列印流相關類的相關定義和繼承關系,了解其相關功能,學會使用列印流實作資料的簡單輸出和格式化輸出的功能。

列印流

但是既然所有的開發者都已經發現了原始中的OutputStream功能的不足,設計者也一定可以發現,是以為了解決輸出問題,在java.io包中提供有列印流:PrintStream、PrintWriter。

PrintStream:

public class PrintStream extends FilterOutputStream implements Appendable, Closeable
構造方法:public PrintStream(OutputStream out);           

PrintWriter:

public class PrintWriter extends Writer
構造方法:public PrintWriter(OutputStream out);           
使用列印流優化資料輸出 | 帶你學《Java語言進階特性》之六十五

下面使用PrintWriter來實作資料的輸出操作。

範例:資料輸出

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class JavaAPIDemo {
    public static void main(String[] args) throws Exception {
        File file = new File("d:" + File.separator +"mldn.txt");   //定義操作檔案
        PrintWriter pu = new PrintWriter(new FileOutputStream(file));
        pu.println("姓名:小強子");
        pu.print("年齡:");
        pu.print(78);
        pu.close();
    }
}           

從JDK1.5開始,PrintWriter類裡面追加有格式化輸出的操作支援:

public PrintWriter format(String format, Object... args)           

範例:格式化輸出

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class JavaAPIDemo {
    public static void main(String[] args) throws Exception {
        File file = new File("d:" + File.separator +"mldn.txt");   //定義操作檔案
        PrintWriter pu = new PrintWriter(new FileOutputStream(file));
        String name="小強子子";
        int age=78;
        double salary=72823.6323113;
        pu.printf("姓名:%s、年齡:%d、月收入:%9.2f",name,age,salary);
        pu.close();
    }
}    //姓名:小強子子、年齡:78、收入:72823.63           

比起直接使用OutputStream類,那麼使用PrintWriter、PrintStream類的處理操作會更加簡單。以後隻要是程式進行内容輸出的時候全部使用列印流。

想學習更多的Java的課程嗎?從小白到大神,從入門到精通,更多精彩不容錯過!免費為您提供更多的學習資源。

本内容視訊來源于

阿裡雲大學 下一篇:System類助力标準IO實作 | 帶你學《Java語言進階特性》之六十六 更多Java面向對象程式設計文章檢視此處