Java標準輸入/輸出/錯誤流


只要使用OutputStream物件就可使用System.outSystem.err物件參照。只要可以使用InputStream物件就可以使用System.in物件。

System類提供了三個靜態設定器方法setOut()setIn()stdErr(),以用自己的裝置替換這三個標準裝置。

要將所有標準輸出重定向到一個檔案,需要通過傳遞一個代表檔案的PrintStream物件來呼叫setOut()方法。

import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.File;

public class Main {
  public static void main(String[] args) throws Exception {
    File outFile = new File("stdout.txt");
    PrintStream ps = new PrintStream(new FileOutputStream(outFile));

    System.out.println(outFile.getAbsolutePath());

    System.setOut(ps);

    System.out.println("Hello world!");
    System.out.println("Java I/O  is cool!");
  }
}

上面的程式碼生成以下結果。

F:\website\yiibai\worksp\stdout.txt

標準輸入流

可以使用System.in物件從標準輸入裝置(通常是鍵盤)讀取資料。
當使用者輸入資料並按Enter鍵時,輸入的資料用read()方法每次返回一個位元組的資料。
以下程式碼說明如何讀取使用鍵盤輸入的資料。\n是Windows上的換行字元。

import java.io.IOException;
public class Main {
  public static void main(String[] args) throws IOException {
    System.out.print("Please type   a  message  and  press enter: ");

    int c = '\n';
    while ((c = System.in.read()) != '\n') {
      System.out.print((char) c);
    }
  }
}

由於System.inInputStream的一個範例,可以使用任何具體的裝飾器從鍵盤讀取資料; 例如,可以建立一個BufferedReader物件,並從鍵盤讀取資料一行一次作為字串。

上面的程式碼生成以下結果。

Please type   a  message  and  press enter: System.in.read demo...
System.in.read demo...

範例

以下程式碼說明如何將System.in物件與BufferedReader一起使用。程式不斷提示使用者輸入一些文字,直到使用者輸入Qq來退出程式。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String text = "q";
    while (true) {
      System.out.print("Please type a message (Q/q to quit) and press enter:");
      text = br.readLine();
      if (text.equalsIgnoreCase("q")) {
        System.out.println("We have  decided to exit  the   program");
        break;
      } else {
        System.out.println("We typed: " + text);
      }
    }
  }
}

如果想要標准輸入來自一個檔案,必須建立一個輸入流物件來表示該檔案,並使用System.setIn()方法設定該物件,如下所示。

FileInputStream fis  = new FileInputStream("stdin.txt"); 
System.setIn(fis); 
// Now  System.in.read() will read   from  stdin.txt file

上面的程式碼生成以下結果。

Please type a message (Q/q to quit) and press enter:abc
We typed: abc
Please type a message (Q/q to quit) and press enter:yes or no?
We typed: yes or no?
Please type a message (Q/q to quit) and press enter:yes
We typed: yes
Please type a message (Q/q to quit) and press enter:q
We have  decided to exit  the   program

標準錯誤裝置

標準錯誤裝置用於顯示任何錯誤訊息。Java提供了一個名為System.errPrintStream物件。使用它如下:

System.err.println("This is  an  error message.");