In Java, newly created output streams look at the system line separator property to decide between Unix and Windows line endings, but System.out has already been created by the time your program starts, so altering that property has no effect on that stream.
If you want System.out to use Unix line endings, despite running on Windows, is there a way to do this other than eschewing println() and always using print("...\n")?
You can manually set System.out. I sometimes use it to redirect prints to a file.
For example:
System.setOutput(new PrintStream("whatever_file.txt"));
In a similar sense, you can change the PrintStream to take your line endings into account.
Alternatively you can directly set the property of the line ending character:
System.setProperty("line.separator", "\n");
This could also be done when creating the JVM by the usual property setter:
java -jar bla.jar -Dline.seperator='\n'
Related
How can we redirect the eclipse console output to a file? I can:
Run Configuration->Commons->Select a file.
Use System.setOut(PrintStream) and System.setErr(PrintStream).
The problem with 1) is that I need to record console output to different files instead of one file.
The problem with 2) is that it only stores console output generated by System.out.println() or stacktrace of an exception thrown. It does not capture other kind of outputs e.g. log4j warnings etc.
How can we redirect console output to different files programmatically?
Go to run as and choose Run Configurations -> Common and in the Standard Input and Output you can choose a File also.
You could use a "variable" inside the output filename, for example:
/tmp/FetchBlock-${current_date}.txt
current_date:
Returns the current system time formatted as yyyyMMdd_HHmm. An optional argument can be used to provide alternative formatting. The argument must be valid pattern for java.util.SimpleDateFormat.
Or you can also use a system_property or an env_var to specify something dynamic (either one needs to be specified as arguments)
You can set the output of System.out programmatically by doing:
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("/location/to/console.out")), true));
Edit:
Due to the fact that this solution is based on a PrintStream, we can enable autoFlush, but according to the docs:
autoFlush - A boolean; if true, the output buffer will be flushed
whenever a byte array is written, one of the println methods is
invoked, or a newline character or byte ('\n') is written
So if a new line isn't written, remember to System.out.flush() manually.
(Thanks Robert Tupelo-Schneck)
To solve the problem I use ${string_prompt} variable.
It shows a input dialog when application runs. I can set the date/time manually at that dialog.
Move cursor at the end of file path.
Click variables and select string_prompt
Select Apply and Run
We can do this by setting out variable of System class in the following way
System.setOut(new PrintStream(new FileOutputStream("Path to output file"))). Also You need to close or flush 'out'(System.out.close() or System.out.flush()) variable so that you don't end up missing some output.
Source : http://xmodulo.com/how-to-save-console-output-to-file-in-eclipse.html
In Java, I want to intercept my process's stdout and stderr. I don't want to prevent it from going to the console/default destination eventually, but at every newline, I need to copy that line into my own log file (with some formatting and HTMLification). The only way I can see to do this is something like this -- which might work, but I'm worried about different charsets, want to eventually format output the same way as before instead of suppressing it, and I need to handle it at every newline, not when it feels like flushing (even with auto-flush = true).
Is there a library of some sort that makes this easier?
but at every newline, I need to copy that line into my own log file (with some formatting and HTMLification).
Why don't you consider the classic Unix utility tee? A demo:
tail -f source | tee tee.sink
echo "foo" >> source -- you should see "foo" also on your terminal
cat tee.sink should display foo.
Or did I misunderstand what you want?
I am trying to add a Java from to a Visual Prolog generated executable by running it as a process.
I have used this answer to implement the process interaction. My Visual Prolog expects a number from the command line, it even validates it (whether it is a Prolog term or not), but when running from Java, it does not recognize input as valid. Are those scape chars turning my number into a string?
When I try to remove them, my Java program hungs and the Visual Prolog executable does not respond. I think it is like pressing the enter button.
\r\n is an EOL (end-of-line) sequence in Windows.
If the input is read line-oriented then the consuming code won't process the line until EOL (or EOF) is sent - this will make the consumer appear to "hang" while it's really juts patiently waiting for the rest of the line. Consider Scanner.nextLine in Java: nextLine won't return until a full line is ready!
Solution: send the EOL with the appropriate input to Visual Prolog; or close the input stream.
Also see also "line.separator", perhaps. However, the various println (print line) methods should already include the appropriate EOL.
\r is carriage return CR
\n is linefeed LF
many textual protocols require you to use CR+LF and some require to recognize on LF.
It is like starting a newline in text in Windows
It's necessary if and only if the target process requires it.
You state that your process 'requires a number from the command line', but if you're feeding it input through its 'stdin' that can't be the case.
Instead it appears to require a number via a line entered to the console.
In either case the word 'line' indicates the need for a line terminator.
The referenced example is using pipes (redirecting stdin and stdout) to communicate between the processes, but you say your program expects a number on the command line.
On standard console all things are printed in white whether we have written it in System.out or System.err. In IDE(for me Eclipse) we can see different color output on console for both. i.e. black for System.out and red for System.err.
Is System.err is only provided for use in IDEs? Cause on cmd we can not distinguish System.out and System.err. Both are printed in same color.
These are two different output streams that are available in most of OS's. You don't have them color coded due to settings of your terminal/command line environment. On the other hand your IDE provides different visualization for different streams.
If you wanted to color them, consider using ANSI escape sequences.
This is a relict from the unix world, where most functionality is available as unix commands which were intended to be chained. The output of one command is used to feed another like here:
grep -i 'token' file | mail peter#address.de
The pipe symbol only redirects the stdout (System.out), but not the stderr (System.err). So error messages would be seen on the console, and the regular output would go to the mail command.
If there were just one stream, one could not distinguish between them.
Windows, not relying on the command line (This changed in Windows Server 2008!) didn't invent again but just took the unix concepts and made them available in their dos commands, too. It is just that nearly no Windows only users usually know what they are good for.
From system-in-out-error:
System.err is a PrintStream.
System.err works like System.out
except it is normally only used to
output error texts. Some programs
(like Eclipse) will show the output to
System.err in red text, to make it
more obvious that it is error text.
From JLS:
20.18.3 public static PrintStream err;
The initial value of this variable is
a "standard" error output stream,
already open and ready to accept
output data. Typically, this
corresponds to display output or
another output destination specified
by the host environment or user. By
convention, this output stream is used
to display error messages or other
information that should come to the
immediate attention of a user even if
the principal output stream, the value
of the variable out, has been
redirected to a file or other
destination that is typically not
continuously monitored. Note that this
field is not final, so its value may
be updated if necessary.
From Java World 02-qa-1220-console.html
Other post in Stackoverflow coloring-text-with-java-in-windows
System.out goes to the standard output stream (stdout) and System.err goes to the standard error stream (stderr). See standard streams for details and how you can control where they go. Eclipse just conveniently colour codes them for you so you can distinguish them in one view.
Both System.out and System.err always exist in Java.
Depending on your console it might be possible to get it to display the two streams in a different colour.
Example use:
try {
Class.doSomething(myFile);
} catch (Exception e){
System.err.println("Fatal error performing doSomething: " + e);
System.exit(-1);
}
I have the Java code below running on Unix (both AIX and Linux), but it doesn't work. If I run this code the file q1.01 is not compressed, and I don't get any exceptions thrown (The file q1.01 exists, and I expect to find the file q1.01.Z after the command runs.) At the command prompt if I type "which compress" it reports back with "/usr/bin/compress". If I type the command "/usr/bin/compress q1.01" at the Unix prompt it works fine. Any ideas on what might be wrong?
String cmd = "/usr/bin/compress q1.01";
Runtime.getRuntime().exec(cmd);
[Later edit: the problem was in the initial description; the OP was passing a wildcard and not q.01. So my answer below is wrong, except for the part in bold. I'm leaving it so the comments after it will make sense.]
It's trying to run /usr/bin/compress as the program name without arguments.
There are many forms of the Runtime.exec() method. You're using the .exec(String) version, which just takes the executable. Instead, you need to use the .exec(String[]) array version, which takes the executable in String[0] and the parameters in String[1..].
.exec() wants a String array for passing arguments.
Try
String[] cmd = new String[] { "/usr/bin/compress", "q1.01" };
Runtime.getRuntime().exec(cmd);
Note that .exec does not call the local command shell. That means we have to do, among other things, wildcard expansion and even some argument parsing before calling .exec(). This is why you can't just pass it your full command line.
There were a couple of problems. One was that I had tried using wildcards, and since the shell isn't invoked they weren't being expanded. The other problem was that I had created very small test files like this: "echo 'abc' >q1.01". This file was so small that compress couldn't compress it any further and so left it alone. (Stupidly, I think when I typed in the command at the shell I used a different filename, which did compress.)
Thanks everyone for the answers. It did help!
You probably need to use an absolute path to the file. Capture the output though, to see what the problem is - see this page for info on how to do that.
This site may be able to provide some clues.
If the process input stream is null, I suspect that Java wasn't even able to spawn the subprocess. What does Process#exitValue() return?
I'd recommend using strace to see what actually happens on the system-call level. The actual exec() arguments and return code would be especially interesting to see.