初學Java時就會學到 System.out.print 這標準輸出的方法將資料顯示在螢幕上。

但是如果開發過程沒有使用例如 log4j 這類log的工具,進行開發,如何可以透過以下技巧讓System.out 達到log的效果。

 

關鍵程式碼如下:

1
2
PrintStream ps = new PrintStream(".log.txt");
System.setOut(ps);

透過System.setOut 將原本的輸出串流改到 log.txt

此後所有的 System.out 的資料都會寫到 log.txt 之中。

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class RedirectOutputStream {
	
	public static void main(String[] args) {
		PrintStream out = System.out;
		
		try {
			PrintStream ps = new PrintStream(".log.txt");
			System.setOut(ps);
			
			int age = 18;
			System.out.println("年齡變數成功定義為 ,初始值為18");
			String sexString = "女";
			System.out.println("性別變數成功定義為 ,初始值為女");
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
}

 

程式碼專案(連結)

arrow
arrow
    文章標籤
    java
    全站熱搜
    創作者介紹
    創作者 Lung-Yu,Tsai 的頭像
    Lung-Yu,Tsai

    Lung-Yu,Tsai 的部落格

    Lung-Yu,Tsai 發表在 痞客邦 留言(0) 人氣()