本文是基於Linux環境運行,讀者閱讀前需要具備一定Linux知識
Java的標准輸入/輸出分別通過System.in和System.out來代表,默認情況下它們分別代表鍵盤和顯示器,當程序通過System.in來獲取輸入時,實際上是從鍵盤讀取輸入,當程序試圖通過System.out執行輸出時,程序總是輸出到屏幕
System類里提供三個重定向標准輸入/輸出的方法:
- static void setErr(PrintStream err):重定向“標准”錯誤輸出流
- static void setIn(InputStream in):重定向“標准”輸入流
- static void setOut(PrintStream out):重定向“標准”輸出流
將System.out的輸出重定向到文件,而不是在屏幕上輸出
代碼1-1
import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; public class RedirectOut { public static void main(String[] args) { if (args == null || args.length == 0) { throw new RuntimeException("請輸入路徑"); } PrintStream ps = null; try { String[] books = new String[] { "Java編程思想", "編譯原理", "算法" }; ps = new PrintStream(new FileOutputStream(args[0])); System.setOut(ps); for (String book : books) { ps.println(book); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (ps != null) { ps.close(); } } } }
代碼1-1運行結果:
root@lejian:/home/software/.io# java RedirectOut books root@lejian:/home/software/.io# cat books Java編程思想 編譯原理 算法
代碼-2中用FileInputStream創建了一個文件輸入流,並使用System的setIn()方法將系統標准輸入流重定向到該文件輸入流,運行代碼1-2,程序不再等待用戶輸入,而是直接輸入用戶所給的路徑所對應的文件內容
代碼1-2
import java.io.FileInputStream; import java.io.IOException; import java.util.Scanner; public class RedirectIn { public static void main(String[] args) { if (args == null || args.length == 0) { throw new RuntimeException("請輸入路徑"); } FileInputStream fis = null; try { fis = new FileInputStream(args[0]); System.setIn(fis); Scanner sc = new Scanner(System.in); sc.useDelimiter("\n"); while (sc.hasNext()) { System.out.println(sc.next()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
代碼1-2運行結果:
root@lejian:/home/software/.io# java RedirectIn books Java編程思想 編譯原理 算法