2013-04-05 252 views
0

我想在文本文件中顯示我的控制檯輸出。從java中將控制檯輸出寫入文本文件

public static void main(String [ ] args){ 
    DataFilter df = new DataFilter(); 
    df.displayCategorizedList(); 
    PrintStream out; 
    try { 
     out = new PrintStream(new FileOutputStream("C:\\test1.txt", true)); 
     System.setOut(out); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

我在屏幕上正確顯示了我的結果,但沒有導致文本文件? 測試文件生成但它是空的?

+0

does'df.displayCategorizedList();'print to stdout?那麼你應該把它放在'System.setOut()'後面呢' – 2013-04-05 07:26:31

+0

我是java新手,你能不能給我更多提示請 – 2013-04-05 07:26:42

+0

這個話題似乎已經被相當徹底地處理了[在這裏](http:// stackoverflow。 COM /問題/ 1994255 /如何到寫控制檯輸出到一個-TXT文件)。 – 2013-04-05 07:27:32

回答

5

將系統輸出流設置爲文件後,應打印到「控制檯」。

DataFilter df = new DataFilter(); 
    PrintStream out; 
    try { 
     out = new PrintStream(new FileOutputStream("C:\\test1.txt", true)); 
     System.setOut(out); 
     df.displayCategorizedList(); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } finally { 
     if (out != null) 
      out.close(); 
    } 

同樣使用finally塊來關閉流,否則數據可能不會被刷新到文件。

+0

您將o/p流設置爲文件,然後保存在c文件夾中 – 2013-04-05 07:28:34

0

我建議以下方法:

public static void main(String [ ] args){ 
    DataFilter df = new DataFilter(); 
    try (PrintStream out = new PrintStream(new FileOutputStream("d:\\file.txt", true))) { 
      System.setOut(out); 
      df.displayCategorizedList(); 
    } catch (FileNotFoundException e) { 
     System.err.println(String.format("An error %s occurred!", e.getMessage())); 
    } 
} 

這是使用JDK 7的try-與資源的功能 - 這意味着它有例外(如FileNotFoundException異常)的交易,你必須與它也關閉資源(而不是finally塊)。

如果您不能使用JDK 7,請使用其他響應中建議的方法之一。

相關問題