System.out.println to text file

17,311

Solution 1

You can do,

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

Then any println statement will go into the file.

Solution 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);
}
Share:
17,311

Related videos on Youtube

Sapus Boh
Author by

Sapus Boh

Updated on September 16, 2022

Comments

  • Sapus Boh
    Sapus Boh over 1 year

    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

  • Admin
    Admin over 7 years
    I agree. Or he could use a platform-specific solution such as redirecting output to file in bash: java -jar program.jar > output 2> error-output
  • Tom
    Tom over 7 years
    Prefer to close obvious duplicate questions, instead of farming reputation.