I tried to PrintStream to a text file for writing a bunch of output to a file.
But after the file is created, I was trying to switch back to the standard output just to continue on with other processes, but I have no idea about doing that switch. Seems like I have to setOut to the standard console, but how do I do that?
Below is the code that I used to output to a text file. Any ideas?
PrintStream out = new PrintStream(fistr);
System.setOut(out);
Thanks.
Why don't you save it before modifying it, so that you can go back?
PrintStream standard = System.out;
PrintStream out = new PrintStream(fistr);
System.setOut(out);
/*
some other stuff
*/
System.setOut(standard);
Related
Code for redirecting the print output within the program:
try
{
System.out.println("Print on console");
// Store console print stream.
PrintStream ps_console = System.out;
File file = new File("C:/Users/John/Desktop/compiletest/output" + trialNum + ".txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.out.println("Print in the file !!");
// Set console print stream.
//System.setOut(ps_console);
System.out.println("Console again !!");
}
catch(Exception e)
{
System.out.println("Mission failed, we'll get em next time");
}
This method works fine if it is implemented in the program I want to redirect its output. In my case I want a separate class that will redirect the output of a certain program to a txt file.
If there is a simpler way to complete this task I am greatly inclined to hear.
This seems like a perfect usage example for a logging framework.
SLF4J
Log4J
Java Logging
There are many other libraries you can use. In general it is always preferable to use a separate stream for files - if you must redirect System.out it could be useful to keep the original PrintStream before you change it so that you can still write to the console if you need to:
PrintStream ORIGINAL_SOUT = System.out;
System.setOut(ps);
System.out.println("ABC"); // Uses file
ORIGINAL_SOUT.println("ABC"); // Uses console
A simple usage example of a logging framework (from the first linked library):
private static final Logger logger = LoggerFactory.getLogger(YourClass.class);
logger.debug("A message at DEBUG level");
logger.info("A message at INFO level");
logger.warn("A message at WARN level");
logger.error("A message at ERROR level");
I think you should create Temporary function for holding and storing your data with temporary and then execute your transactions anyway you want. Finally you can store your data wherever you want with permanently. This is the most known method I know. You should check the link for understanding easier.
http://www.daveoncsharp.com/2009/09/how-to-use-temporary-files-in-csharp/
Logging software (such as SLF4J,Log4J etc)is better option.
It has different ways to create file,different file formats, rolling appenders(based on dates/sequence/size), logs based on priorities
How can I redirect an output in java?
I am running a program in eclipse. My code is as follows:
public static void main(String[] args) throws Exception{
/* Redirect output to file */
File file = new File("fileName");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
OtherClass.main(args);
}
Without the output redirection I wrote above, the code returns some values in black and some in red (which are not errors, but parameters called in OtherClass).
The redirection above writes the text that appeared in black in the eclipse console in my file, but the output in read is written on console and not in my file.
How can I do the contrary and print the red text in my file and not the black one? And why does eclipse use different colors for this output?
How can I do the contrary and print the red text in my file and not the black one?
Instead of redirecting output from standard output (System.out) to file, redirect output from error stream (System.err). In other words instead of
System.setOut(ps);
use
System.setErr(ps);
// ^^^
And why does eclipse use different colors for this output?
So you could see which output comes from System.out (black), and which from System.err (red - which handles printing Exceptions).
Calling System.setOut() redirects stdout, you need to call System.setErr() to redirect stderr - something like,
// System.setOut(ps);
System.setErr(ps); // <-- for std err
Red output in the Eclipse console is text being printed onto the standard error stream (System.err). In order to accomplish that only the text being printed in red is written to the file you need to replace your call to System.setOut(ps); with System.setErr(ps);.
I have a program that is only meant to be terminated by pressing Ctrl + C. In this program I write to an external file using:
File logFile = new File("output.txt");
PrintWriter log_file_writer = new PrintWriter(logFile);
log_file_writer.println("TEXT");
However because I don't know when the program will be terminated, I can't close the file using:
log_file_writer.close();
I think this is resulting in no text appearing in the output file.
Would anyone have a solution for this?
Thank you for your help.
log_file_writer.flush();
will push the content to disk
As the javadoc says:
PrintWriter(File file) Creates a new PrintWriter, without automatic line flushing, with the specified file.
Therefore, you need to flush the data you want to print that is actually buffered:
log_file_writer.flush();
You did not flush the content, I always use the autoFlush argument, but it is not available with File:
PrintWriter log_file_writer = new PrintWriter(new FileOutputStream("output.txt"),true);
but you can also use log_file_writer.flush(); after each write.
I am trying to save the content of the java console into a text file but each time I close the program the text file goes blank and rewrites to it. i.e. if I write to a file today, close the program and come back and run it again tomorrow, it has remembered the information written to it.
You want to open the OutputStream in append mode. Demo code:
PrintWriter out = new PrintWriter(
new FileOutputStream(new File(filename), true));
What you experience is the normal behavior when you write a stream to a file, and this is not specific to the Java API.
In Java, I have redirected System.out: System.setOut("someText.txt"); to write to a text file. I would like to run this program once an hour, and would like to append each set of print statements to the end of the file. For example suppose at hour 1, my program runs, prints "Hello\n" and then quits. Then at hour 2, my program runs, prints "hello again\n", and then quits.
If this happened I would like the contents of my text-file to be something like:
Hello
Hello again
Currently, I am just overwriting the text file.
How can I append to the end of the text file with this redirected printStream?
EDIT How can I also print to the console?
When you build the FileOutputStream use the following:
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
from the JAVADOC
Code example:
OutputStream outStream = new FileOutputStream("file1.txt",true);
Use
OutputStream printStream = new OutputStream(new FileOutputStream("someText.txt", true));
System.setOut(printStream);
the answers by #Frank and #Petr Mensik are correct. But just in case you wanted to try something different:
System.out.append("Hello World\n") should do the trick. Hence, instead of doing a System.out.print, you do a System.out.append
The simplest answer is not to do this using Java code, but to use tee; trying to reimplement tee in Java is just reinventing a square wheel. Just do this:
java -jar yourapp.jar | tee -a output.log
On Windows? Install MinGW and/or Cygwin. :-)