Eclipse freezes when writing to the stdout audio bytes [duplicate] - java

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

Related

What is System.out exactly?

I noticed that any call to System.out.println() from a JAR file that hasn't been started by the command line (i.e. a Runnable JAR file started by user with double-click) won't open the console.
After doing some research, I found multiple answers on the site:
System.out.println in jar
There is no problem doing like that. But where do you expect to see the output?
What happens to “System.out.println()” in executable jar?
If you run the code in some way that doesn't attach a console - such as javaw on Windows, which is the default program associated with executable jar files - then the output won't go anywhere. It won't cause any errors - the text will just be lost.
From what I understand, System.out does not represent the console. It does represent data which can be handled by anything that needs to display it.
Am I right?
What is System.out exactly?
How do I open the console from a Runnable JAR file started by user with double-click?
Processes in modern operating systems (and for that matter, several older operating systems) get three standard "streams" associated with them:
Standard in: Stream-based input (stdin)
Standard out: Stream-based output (stdout)
Standard error: Stream-based error output (stderr)
Collectively (and creatively) they're called the standard streams.
System.in, System.out, and System.err are, by default, Java's standard mechanism for writing to those streams.
Programs invoked from the command line are run in an environment where keystrokes in the command line go to stdin, and the output of both stdout and stderr shows as text in the console. They can be redirected to files, etc.
Programs launched via GUIs frequently don't have those streams hooked to anything you can see.
I say "by default" above because you can use calls on System to change where those streams point (they have creative names like setIn, setOut, and setErr.)
How do I open the console from a Runnable JAR file started by user with double-click?
There's a false correlation there: The fact that the jar is runnable is not why you don't see the streams. If you run a runnable jar at the command line, you'll see its standard output.
Whether you can see that output if you run it without it being associated with a console of some kind will depend on how you're running it and, potentially, how it's written. Many GUI frameworks will redirect standard out and err to a log file. Or the app may offer debugging options that do so. There's no one standard answer there (no pun).
Here, System.out represents the output stream - where your output will go. By default it is set to console. But you can change it to other like - text file. Most often, in large application it is used for logging (usually by new programmer, bad idea). In this case you can see the output in appropriate log file.
System is final class from java.lang package(default package in java) and cannot be instantiated.
out is a static member field of System class and is of type PrintStream and its access specifiers are public final.
println – is an overloaded method of PrintStream class. println prints the argument passed to the standard console and a newline. There are multiple println overloaded methods with different arguments. Every println makes a call to print method and adds a newline. Internally, print calls write() and write() takes care of displaying data to the standard output window.
Here it is how it should look in the inside:
//the System class belongs to java.lang package
class System {
public static final PrintStream out;
//...
}
//the Prinstream class belongs to java.io package
class PrintStream{
public void println();
//...
}
We therefore don't need to ever instantiate a System object to print messages to the screen; we simply call the println method on the System class's public static PrintStream member, out.
But you cannot create an object of PrintStream and call the println function. When you want to print to the standard output, then you will use System.out. That's the only way. Instantiating a PrintStream will allow you to write to a File or OutputStream you specify, but don't have anything to do with the console.
However, you can pass System.out to PrintStream and then invoke println on PrintStream object to print to the standard output. Here is a small example:
import java.io.*;
public class SystemOutPrintlnDemo
{
public static void main(String[] args)
{
//creating PrintStream object
PrintStream ps = new PrintStream(System.out);
ps.println("Hello World!");
ps.print("Hello World Again!");
//Flushes the stream
ps.flush();
}
}

System.out to Unix line endings on Windows

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'

Use of System.err.println() in Java

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);
}

How to make System.err write in one block

I'd like to solve following issue: imagine that you are doing lots of outputs in System.out, and from time to time there is an Exception thrown. When you look into the console, you can see that the exception's trace text is mixed up with normal output done by System.out. I understand that these two are different streams (System.out and System.err) and I guess that the output of the exception is done internally by some other thread, that is why it is mixed up.
However, is it somehow possible for the code to stop until output for the exception is done? The only solution I can think of is to put Thread.sleep, but maybe there might be some option I am not aware of.
Just curious really :) It'd be nice for debugging (that's the reason I ask, because reading the output and exceptions mixed up in between is terrible)
If you have multiple threads and their output is getting interleaved, you should think about using a logging facility rather than trying to share the stderr and stdout-
http://download.oracle.com/javase/6/docs/api/java/util/logging/package-summary.html
Or apache's log4j:
http://logging.apache.org/log4j/1.2/
How about redirecting System.err to a file?
System.setErr( ... );
The problem needs to be solved elsewhere, in the process which merges two file streams into the output you see - by only printing out a line when it is done. Since that is most likely not an option to you if you are talking about the "java.exe" output, you need to investigate elsewhere.
I have not tested, but I would start with having a look at invoking flush() on System.out before you send output to System.err.
When java implicitly imports the lang (java.lang.*) package, the System class has 2 standard output streams.
System.err
System.out
And because these both output to the same standard output, you have to choose one and change it from standard output to file output. My recommendation would be to change the System.err output like so:
import java.io.* ......
System.setErr (new PrintWriter (new FileWriter ("Errors.txt")));
Hope this helps!
EDIT
Sorry, can't leave comments yet, but the logging idea above is very good. Depending on what you are doing, logging will be an optimal solution. But I try to avoid logging because it tends to become very memory extensive if it is used too much.
Write to a separate stream in memory to format your output, then write the single string at once. You may still end up with your single string in the middle of an exception's text, though. Fundamentally what you are doing requires synchronization, or a separate stream (think one output file per thread).
I don't see how Thread.sleep will do anything other than complicate the issue.
Create a new PrintStream to file descriptor 2 with autoflush set to false.
System.setErr(new PrintStream(new FileOutputStream(FileDescriptor.err, false, "UTF-8")));
Just make sure to call System.err.flush after important error messages.
If you want to merge stderr into stdout, you can do the above but with FileDescriptor.out.

How to make Java console input dissapear after pressing enter

I'm using the Scanner class to take some input from the user through the console. Whenever the user inputs something in the screen and presses enter the input stays on screen for example:
This is the prompt
// User writes command and presses enter
command
output of command goes here
//Use writes command3
command
output of command goes here
command3
output of command3 goes here
Is there anyway I can make the command entered not stay in the console after pressing enter?
For example:
//User writes command
output of command goes here
Short answer: no, not from directly within Java. Java has very limited control over the console: you can only read and write to it. Whatever is displayed on the console cannot be erased programmatically.
Long answer: in Java, all console operations are handled through input and output streams—System.in is an input stream, and System.out and System.err are output streams. As you can see for yourself, there is no way to modify an output stream in Java—essentially, all an output stream really does is output bytes to some destination (which is one reason why it's called a "stream"—it's one-way).*
The only workaround I can see is to use a Console object (from System.console()) instead. Specifically, the readPassword() method doesn't echo whatever the user types back to the console. However, there are three problems with this approach. First of all, the Console class is only available in Java 1.6. Second, I wouldn't recommend using this for input other than passwords, as it would make entering commands more troublesome than it's supposed to be. And third, it still wouldn't erase the prompt from the screen, which would defeat the purpose of what you're trying to achieve, I'd think.
* - Technically speaking, System.out and System.err are both instances of PrintStream, but PrintStream is pretty much just a flexible version of OutputStream—a PrintStream is still like a normal output stream in that outputting is a one-way operation.
You will struggle to do this with the standard library.
If you don't want to do it yourself, you may be able to do this with a 3rd party library like JLine.
huh - I always assumed that if you sent backspace characters ('\b') to sysout that it would clear - but I never actually tried it (don't do much console programming these days).
Haven't tried that, but the bottom of this thread seems to indicate that it should work.
Note that this might not work in an IDE console, but may work in a regular OS console...
I'll leave actually proving for certain that it works as an exercise to the OP :-)

Categories

Resources