Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.out.println to text file

Tags:

java

file

output

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

like image 259
Sapus Boh Avatar asked Dec 18 '22 13:12

Sapus Boh


2 Answers

You can do,

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

Then any println statement will go into the file.

like image 158
Codebender Avatar answered Dec 29 '22 12:12

Codebender


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);
}
like image 41
DimaSan Avatar answered Dec 29 '22 12:12

DimaSan