我們可以使用System.out和System.err對象引用,只要我們可以使用OutputStream對象。
我們可以使用System.in對象,只要我們可以使用InputStream對象。
System類提供了三個靜態(tài)設(shè)置器方法setOut(),setIn()和setErr(),以用您自己的設(shè)備替換這三個標(biāo)準(zhǔn)設(shè)備。
要將所有標(biāo)準(zhǔn)輸出重定向到一個文件,我們需要通過傳遞一個代表我們文件的PrintStream對象來調(diào)用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!"); } }
上面的代碼生成以下結(jié)果。
我們可以使用System.in對象從標(biāo)準(zhǔn)輸入設(shè)備(通常是鍵盤)讀取數(shù)據(jù)。
當(dāng)用戶輸入數(shù)據(jù)并按Enter鍵時,輸入的數(shù)據(jù)變得可用,read()方法每次返回一個字節(jié)的數(shù)據(jù)。
以下代碼說明如何讀取使用鍵盤輸入的數(shù)據(jù)。\n是Windows上的新行字符。
import java.io.IOException; public class EchoStdin { 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.in是InputStream的一個實例,我們可以使用任何具體的裝飾器從鍵盤讀取數(shù)據(jù);例如,我們可以創(chuàng)建一個BufferedReader對象,并從鍵盤讀取數(shù)據(jù)一行一次作為字符串。
上面的代碼生成以下結(jié)果。
以下代碼說明如何將System.in對象與BufferedReader一起使用。程序不斷提示用戶輸入一些文本,直到用戶輸入Q或q退出程序。
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); } } } }
如果我們想要標(biāo)準(zhǔn)輸入來自一個文件,我們必須創(chuàng)建一個輸入流對象來表示該文件,并使用System.setIn()方法設(shè)置該對象,如下所示。
FileInputStream fis = new FileInputStream("stdin.txt"); System.setIn(fis); // Now System.in.read() will read from stdin.txt file
上面的代碼生成以下結(jié)果。
標(biāo)準(zhǔn)錯誤設(shè)備用于顯示任何錯誤消息。Java提供了一個名為System.err的PrintStream對象。我們使用它如下:
System.err.println("This is an error message.");
更多建議: