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.out
attribute to be the supplied PrintStream value.There are analogous methods (
setIn
andsetErr
) for changing the standard input and error streams; refer to thejava.lang.System
javadocs for details.A more general version of the above is this:
If
append
istrue
, the stream will append to an existing file instead of truncating it. Ifautoflush
istrue
, the output buffer will be flushed whenever a byte array is written, one of theprintln
methods is called, or a\n
is 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 either:
out
stream passed as a parameter rather than writing toSystem.out
.Changing
System.out
may cause nasty surprises for other code in your JVM that is not expecting this to happen.You can use System.setOut() at the start of your program to redirect all output via
System.out
to your ownPrintStream
.I am using absolute path for the FileWriter. It is working for me like a charm. Also Make sure the file is present in the location. Else It will throw a FileNotFoundException. This method does not create a new file in the target location if the file is not found.
to preserve the console output, that is, write to a file and also have it displayed on the console, you could use a class like:
and used as in:
(just an idea, not complete)
This is my idea of what you are trying to do and it works fine:
The easiest way to write console output to text file is