2011-03-24 47 views

回答

2

重定向它像这样在你的终端。

java ClassName > your-file 

or 

java ClassName 1> your-file 

这里
1表示标准输出。
2代表标准错误。
0代表标准输入。

使用>>为追加模式,'<'为输入模式。

如果你需要错误和输出流重定向到同一个文件, 尝试

java ClassName 2>&1 your-file 

或者在代码中使用了Java的below API调用。

System.setErr(PrintStream err); 

System.setIn(InputStream in); 

System.setOut(PrintStream out); 
0

使用日志记录而不是system.out。检查log4j或其他日志apis。这也将帮助您在使用打印信息,仅调试,只有错误等

此外,如果你想设置系统出来,你可以做到这一点通过命令文件>>文件

1

试试这个

public class RedirectIO 
{ 



public static void main(String[] args) 
{ 
    PrintStream orgStream = null; 
    PrintStream fileStream = null; 
    try 
    { 
     // Saving the orginal stream 
     orgStream = System.out; 
     fileStream = new PrintStream(new FileOutputStream("out.txt",true)); 
     // Redirecting console output to file 
     System.setOut(fileStream); 
     // Redirecting runtime exceptions to file 
     System.setErr(fileStream); 
     throw new Exception("Test Exception"); 

    } 
    catch (FileNotFoundException fnfEx) 
    { 
     System.out.println("Error in IO Redirection"); 
     fnfEx.printStackTrace(); 
    } 
    catch (Exception ex) 
    { 
     //Gets printed in the file 
     System.out.println("Redirecting output & exceptions to file"); 
     ex.printStackTrace(); 
    } 
    finally 
    { 
     //Restoring back to console 
     System.setOut(orgStream); 
     //Gets printed in the console 
     System.out.println("Redirecting file output back to console"); 

    } 

} 

}

希望它能帮助。

相关问题