filename" I have a peculiar problem. I have a Java program that starts with the command...">

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

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

cat input_file_name | ./script_name > file_output_name 

script_name script just does: java myprogram

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

I know that this is possible because some of them already come from some class in the library that I use from my java program. However, I cannot find the exact source of these prints, so I do not know how this is encoded.

Thanks for any help.

+4
source share
4 answers

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

It will switch to another "device" (stderr instead of stdout) and it will not be redirected.

+1
source

The simple answer is to write these messages to System.err , not System.out .

This will work as > redirects standard output but not standard error. (You can redirect the standard error, but the shell syntax is different, for example foo 2> /tmp/somefile .)

A more complex alternative is to modify 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 PrintWriter and write to this stream, not System.out . With a little refactoring, you can structure your program so that you can use it anyway.

+2
source

With what you showed, you only redirect the standard version (stdout). Instead, you can write something standard error (stderr) to show it on the console. In Java, this can be done using System.err.println(...) and its associated methods.

+1
source

Please note that if a Java program writes to standard output, it cannot control where its output is redirected, depending on how the program is called from the command line.

If this is clear, you can redirect standard output to the console only by simply removing the > file_output_name part from this command.

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

0
source

Source: https://habr.com/ru/post/1385715/


All Articles