System.out.println to text file

匆匆过客 提交于 2019-12-23 12:44:41

问题


I was searching a way to get System.out.println texts and save them on a .txt file, for example:

    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 .txt file to the output, any ideas? Thank you


回答1:


You can do,

PrintStream fileStream = new PrintStream("filename.txt");
System.setOut(fileStream);

Then any println statement will go into the file.




回答2:


First you need to declare a String text that contains your message you want to output:

String text = "Java vendor: " + System.getProperty("java.vendor");

Then you can use try-with-resources statement (since JDK 7) which will automatically close your PrintWriter, when all the output done:

try(PrintWriter out = new PrintWriter("texts.txt")  ){
    out.println(text);
}



回答3:


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 :

How to write console output to a txt file



来源:https://stackoverflow.com/questions/39556794/system-out-println-to-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!