2016-03-02 114 views
2

我的代碼需要程序在文本文件中打印一組數字。如何在控制檯中打印和在文本文件中打印

因此,在此期間,我想改變我的輸出流:

System.setOut(new PrintStream(new FileOutputStream("data.txt"))); 

那麼,如何將返回打印控制檯?

任何幫助,將不勝感激。 謝謝。

+0

爲什麼要用' System.out.print'而不是將'PrintStream'傳遞給執行打印和打印的代碼而不是傳遞給'PrintStream'?如果這是不可能的:將'System.out'存儲到變量,更改'System.out',打印某些內容,將'System.out'設置爲舊值。 – fabian

回答

0

這個例子可以幫助您:

https://github.com/dreedyman/Rio/blob/master/rio-start/src/main/java/org/rioproject/start/LogManagementHelper.java#L45

static void redirectIfNecessary() { 
    /* If we have been exec'd by Rio (such as a service that has been declared to be forked, 
    * stdout and stderr have already been redirected */ 
    if(System.getenv("RIO_EXEC")==null && System.console()==null) { 
     redirectToLogger(); 
    } 
} 

static void redirectToLogger(){ 
    System.setOut(new PrintStream(System.out){ 
     public void print(String s){ 
      stdOutLogger.info(s); 
     } 
    }); 
    System.setErr(new PrintStream(System.err){ 
     public void print(String s){ 
      stdErrLogger.error(s); 
     } 
    }); 
} 
0

下面的例子可能會有所幫助....

addWindowListener(new WindowAdapter() { 
     public void windowActivated(WindowEvent e) { 
//   EditorConsole.systemOut.println("editor window activated"); 
      base.handleActivated(Editor.this); 
//   mode.handleActivated(Editor.this); 
      fileMenu.insert(base.getSketchbookMenu(), 2); 
      fileMenu.insert(base.getRecentMenu(), 3); 
//   fileMenu.insert(mode.getExamplesMenu(), 3); 
      sketchMenu.insert(mode.getImportMenu(), 4); 
      mode.insertToolbarRecentMenu(); 
     } 

     // added for 1.0.5 
     // http://dev.processing.org/bugs/show_bug.cgi?id=1260 
     public void windowDeactivated(WindowEvent e) { 
//   EditorConsole.systemErr.println("editor window deactivated"); 
//   mode.handleDeactivated(Editor.this); 
      fileMenu.remove(base.getSketchbookMenu()); 
      fileMenu.remove(base.getRecentMenu()); 
//   fileMenu.remove(mode.getExamplesMenu()); 
      sketchMenu.remove(mode.getImportMenu()); 
      mode.removeToolbarRecentMenu(); 
     } 
     }); 

全碼:http://code.openhub.net/file?fid=LfGSIGX0O67nvFyO4lEKQDA5zxE&cid=80HR_JtEBgg&s=How%20to%20alternate%20between%20printing%20in%20console%20and%20printing%20in%20a%20text%20file&pp=0&fl=Java&ff=1&filterChecked=true&fp=1237&mp,=1&ml=0&me=1&md=1&projSelected=true#L0

相關問題