I have tried to write the console output to a txt file using this code suggestion (http://www.daniweb.com/forums/thread23883.html#) however I was not successful. What’s wrong?
try {
//create a buffered reader that connects to the console, we use it so we can read lines
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//read a line from the console
String lineFromInput = in.readLine();
//create an print writer for writing to a file
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//output to the file a line
out.println(lineFromInput);
//close the file (VERY IMPORTANT!)
out.close();
}
catch(IOException e1) {
System.out.println("Error during reading/writing");
}
You need to do something like this:
The second statement is the key. It changes the value of the supposedly “final”
System.outattribute to be the supplied PrintStream value.There are analogous methods (
setInandsetErr) for changing the standard input and error streams; refer to thejava.lang.Systemjavadocs for details.A more general version of the above is this:
If
appendistrue, the stream will append to an existing file instead of truncating it. Ifautoflushistrue, the output buffer will be flushed whenever a byte array is written, one of theprintlnmethods is called, or a\nis written.I’d just like to add that it is usually a better idea to use a logging subsystem like Log4j, Logback or the standard Java java.util.logging subsystem. These offer fine-grained logging control via runtime configuration files, support for rolling log files, feeds to system logging, and so on.
Alternatively, if you are not “logging” then consider the following:
With typical shells, you can redirecting standard output (or standard error) to a file on the command line; e.g.
For more information, refer to a shell tutorial or manual entry.
You could change your application to use an
outstream passed as a method parameter or via a singleton or dependency injection rather than writing toSystem.out.Changing
System.outmay cause nasty surprises for other code in your JVM that is not expecting this to happen. (A properly designed Java library will avoid depending onSystem.outandSystem.err, but you could be unlucky.)