user1091888
user1091888

Reputation: 43

System.out.println without printing to file when using " > filename"

I have a peculiar problem. I have a Java program that is run with the command :

cat input_file_name | ./script_name > file_output_name

the script_name script just does : java myprogram

My question is : how can I print out something in the console without it being "put in the file_output_name file" (since the > file puts all System.out.prints in that file)

I know this is possible because there are some already that come from some class in a library that I'm using from my java program. However I can't find the exact source of those prints so I don't know how it is coded.

Thank you for any help.

Upvotes: 4

Views: 1016

Answers (4)

paulsm4
paulsm4

Reputation: 121719

The easiest way is to use System.err.println() instead of System.out.

It will go to a different "device" (stderr instead of stdout), and it won't be redirected.

Upvotes: 1

Stephen C
Stephen C

Reputation: 719004

The simple answer is to write those messages to System.err rather than System.out.

This will work since > redirects standard output but not standard error. (You can redirect standard error, but the shell syntax is different; e.g. foo 2> /tmp/somefile.)

A more complicated alternative is to change your program so that it can be called with the name of the output file as an argument. Then open the file, wrap it in a PrintWriter and write to that stream rather than System.out. With a bit of refactoring, you should be able to structure your program so that it can be used either way.

Upvotes: 2

Óscar López
Óscar López

Reputation: 236034

Notice that if a Java program writes to standard output, it can't control where does its output get redirected, that depends on how the program is invoked from the command line.

Having that clear, you can redirect the program's standard output only to the console, by simply removing the > file_output_name part from the command.

Or, you can redirect the output of the program to both the console and a file by using the tee command, take a look at this article which explains in detail how to do it.

Upvotes: 0

ziesemer
ziesemer

Reputation: 28697

With what you've shown, you're only redirecting the standard out (stdout). You can write something to the standard error (stderr) instead to have it show on the console yet. In Java, this can be done by System.err.println(...), and related methods.

Upvotes: 1

Related Questions