4

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

DimaSan
  • 10,315
  • 10
  • 56
  • 68
Sapus Boh
  • 91
  • 1
  • 1
  • 7
  • Duplicate http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java – GreyGoose Sep 18 '16 at 10:48
  • http://www.avajava.com/tutorials/lessons/how-do-i-redirect-standard-output-to-a-file.html – Kumaresan Perumal Sep 18 '16 at 10:52
  • @GreyGoose No since the OP seems require to redirect System.out output to a file – C.Champagne Sep 18 '16 at 11:10
  • 1
    Possible duplicate of [Redirect System.out.println](http://stackoverflow.com/questions/3228427/redirect-system-out-println) – Tom Sep 18 '16 at 11:10
  • *"I was searching"* If you really searched, then you would have found on of the many duplicates. So I doubt your statement. – Tom Sep 18 '16 at 11:11

3 Answers3

9

You can do,

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

Then any println statement will go into the file.

Codebender
  • 13,431
  • 6
  • 40
  • 83
  • 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 –  Sep 18 '16 at 10:53
  • Prefer to close obvious duplicate questions, instead of farming reputation. – Tom Sep 18 '16 at 11:13
1

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);
}
DimaSan
  • 10,315
  • 10
  • 56
  • 68
0

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

Community
  • 1
  • 1
Ankit Tripathi
  • 375
  • 3
  • 13