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);.
Related
I had a very simple request, I have a full code that sorts through an input file and outputs the merged strings properly into the console. My question is can I take this already perfect output from my CONSOLE and simply output it into a seperate .txt fle as well?
I've tried doing a simple
PrintStream printStream = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(printStream);
it does create my output.txt file, but it's always empty?
Option 1: Output via Terminal
Since your script already outputs perfectly to the terminal, you can redirect that output to a file via >
$ ./my-script > output.txt
You can also use the tee command if you still want to see the output in your terminal.
$ ./my-script | tee output.txt
Option 2: Generate file via code
I'm not too familiar with Java / PrintStream but from https://www.tutorialspoint.com/java/io/printstream_print_string.htm, you should see content in your file by:
PrintStream printStream = new PrintStream(new FileOutputStream("output.txt"));
printStream.print("foo");
printStream.flush();
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
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);
Is it possible to tell Eclipse to show only errors in the console ?
It could be useful as I'm using external libraries that use the output to display unwanted data. I know that there is a button "Show Console when standard error changes", but, I'm looking for a filter rather.
Regards.
Eclipse (the Console view) shows two different outputs: The standard output (System.out) and the error output (System.err). Eclipse itself cannot distinguish between an actual error/exception logged by your programm running, and an external library which writes it copyright/licence information to the error stream.
You can redirect the System.out and/or System.err to another OutputStream using the System.setOut and System.setErr functions. This way you can create your own "Console view" or handle the output yourself. If you implement your custom OutputStream class, you can also send the data to the original OutputStream (original System.out or System.err).
PrintStream oldOut;
oldOut = System.out;
System.setOut(new PrintStream(new OutputStream() {
#Override
public void write(int b) throws IOException {
// handle the "b" or
// send it to old stdout:
oldOut.write(b);
}
}));
// do what you want with the stream and afterwards
System.setOut(oldOut);
Also be aware that it may be a problem if you do it in the UI thread. For me the application always hanged afterwards.
If you redirect these streams you can decide if you will forward it onto the standard output/error.
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. :-)