Java:如何将控制台输出保存到文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21476423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How to save console output to a text file?
提问by JDL Wahaha
For example, in the code, I have: System.out.println("Hello World");
例如,在代码中,我有: System.out.println("Hello World");
The console will print: Hello World
控制台将打印: Hello World
So, I want to save the console output into a text file. Can anyone please hint me through this?
所以,我想将控制台输出保存到一个文本文件中。任何人都可以通过这个提示我吗?
采纳答案by Subhrajyoti Majumder
System class provide you a way to dump output in different stream which is System#setOut(PrintStream out)
System 类为您提供了一种在不同流中转储输出的方法 System#setOut(PrintStream out)
Using this method you can pass you FileInputstream to System.setOut
and you can save the console output.
使用此方法,您可以将 FileInputstream 传递给System.setOut
并保存控制台输出。
PrintStream printStream = new PrintStream(new FileOutputStream(file));
System.setOut(printStream);
One interesting part of this question is though out
is declared as final in System class but still you reassign this by System#setOut
.
这个问题的一个有趣的部分是虽然out
在 System 类中被声明为 final ,但你仍然通过System#setOut
.
回答by Abimaran Kugathasan
Create a file, and set as the out of the System class.
创建一个文件,并设置为系统类的out。
File file = new File("out.txt"); //Your file
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.out.println("This goes to out.txt");