天天看點

System類助力标準IO實作 | 帶你學《Java語言進階特性》之六十六

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

在我們日常的生活中,計算機與我們的溝通主要是通過顯示器和鍵鼠裝置來完成的,而在Java中,顯示器的輸出功能和鍵鼠裝置的輸入功能則是依賴于System類的支援,本節将介紹它的相關内容。

【本節目标】

通過閱讀本節目标:你将了解到System類針對IO功能提供的三大系統常量in、out和err的功能和使用方法,學會使用這幾個方法實作鍵盤輸入功能和顯示器輸出功能。

System類對IO的支援

System類是一個系統類,而且是一個從頭到尾一直都在使用的系統類,而在這個系統類之中提供有三個常量:

  • 标準輸出(顯示器):public static final PrintStream out;
  • 錯誤輸出:public static final PrintStream err;
  • 标準輸入(鍵盤):public static final InputStream in;

範例:觀察輸出

public class JavaAPIDemo {
    public static void main(String[] args) throws Exception {
        try {
            Integer.parseInt("a");
        }catch (Exception e){
            System.out.println(e);  //黑色資訊:java.lang.NumberFormatException: For input string: "a"
            System.err.println(e);  //紅色資訊:java.lang.NumberFormatException: For input string: "a"
        }
    }
}           

System.out和System.err都是同一種類型的,如果現在使用的是Eclipse則在使用System.err輸出的時候會使用紅色字型,System.out會使用黑色字型。

  最早設定兩個輸出的操作的目的:System.out是輸出那些希望使用者可以看見的資訊,System.err是輸出那些不希望使用者看見的資訊,如果有需要也可以修改輸出的位置:

  • 修改out的輸出位置:public static void setOut(PrintStream out);
  • 修改err的輸出位置:public static void setErr(PrintStream err);

範例:修改System.err位置

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class JavaAPIDemo {
    public static void main(String[] args) throws Exception {
        System.setErr(new PrintStream(new FileOutputStream(new File("d:" + File.separator +"mldn-err.txt"))));
        try {
           Integer.valueOf("a");
        }catch (Exception e){
            System.out.println(e);
            System.err.println(e);//輸出到檔案裡了
        }
    }
}           

在System類裡面還提供有一個in的常量,而這個常量對應的是标準輸入裝置鍵盤的輸入處理,可以實作鍵盤資料輸入。

範例:實作鍵盤輸入

import java.io.InputStream;
public class JavaAPIDemo {
    public static void main(String[] args) throws Exception {
        InputStream input=System.in;  //此時的輸入流為鍵盤輸入
        System.out.print("請輸入資訊:");
        byte[] data=new byte[1024];
        int len=input.read(data);
        System.out.println("輸入内容為:"+new String(data,0,len));
        //請輸入資訊:www.mldn.cn
        //輸入内容為:www.mldn.cn
    }
}           

但是這樣的鍵盤輸入處理本身是有缺陷的:如果現在的長度不足,那麼隻能接收部分資料,是以這個輸入就有可能需要進行重複的輸入流資料接收,而且在接收的時候還有可能會牽扯到輸入中文的情況,如果對于中文處理不當,則也有可能造成亂碼問題。

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

本内容視訊來源于

阿裡雲大學 下一篇:使用緩沖輸入流優化資料輸入能力 | 帶你學《Java語言進階特性》之六十七 更多Java面向對象程式設計文章檢視此處

繼續閱讀