java System.out.println 到文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39556794/
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
System.out.println to text file
提问by Sapus Boh
I was searching a way to get System.out.println
texts and save them on a .txt file, for example:
我正在寻找一种获取System.out.println
文本并将它们保存在 .txt 文件中的方法,例如:
System.out.println("Java vendor: " + System.getProperty("java.vendor"));
System.out.println("Operating System architecture: " + System.getProperty("os.arch"));
System.out.println("Java version: " + System.getProperty("java.version"));
System.out.println("Operating System: " + System.getProperty("os.name"));
System.out.println("Operating System Version: " + System.getProperty("os.version"));
System.out.println("Java Directory: " + System.getProperty("java.home"));
I want a .txtfile to the output, any ideas? Thank you
我想要一个.txt文件到输出,有什么想法吗?谢谢
回答by Codebender
You can do,
你可以做,
PrintStream fileStream = new PrintStream("filename.txt");
System.setOut(fileStream);
Then any println statement will go into the file.
然后任何 println 语句都将进入文件。
回答by DimaSan
First you need to declare a String text
that contains your message you want to output:
首先,您需要声明一个String text
包含要输出的消息:
String text = "Java vendor: " + System.getProperty("java.vendor");
Then you can use try-with-resourcesstatement (since JDK 7)which will automatically close your PrintWriter
, when all the output done:
然后您可以使用try-with-resources语句(自 JDK 7 起)PrintWriter
,当所有输出完成时,它会自动关闭您的:
try(PrintWriter out = new PrintWriter("texts.txt") ){
out.println(text);
}
回答by Ankit Tripathi
You are using standard System output stream which writes to console.You need to use PrintStream class,create a file and write to it.Example is below :
您正在使用写入控制台的标准系统输出流。您需要使用 PrintStream 类,创建一个文件并写入它。示例如下: