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);
}
Related
I was trying to use System.out.println to help with debugging and I found that it wasn't printing to the console. On inspection I found that my program had created 4 output consoles ( one for Java DB processes, one for the DB server, one for debugging the program, and one for program output ). I found my expected println in an unexpected console - the DB server output.
I would like to get a handle on these outputs. I expected the System class to have a list field of active output consoles ( printstreams ), something like :
ArrayList<PrintStream> getActivePrintOutputs()
But I don't see one. How do I get them?
System has no concept of multiple output streams beyond those specified by out and err, and you can access those by just referencing System.out and System.err respectively.
If there are other consoles or output streams being used, they must have been created by other points in your code (or other points in a library's code that you're using.)
Normally you have only one active System.out output stream, so there is no reason for the system to maintain a list.
If you want to trace all the PrintStreams created you can use instrumentation to track their creation, or put a break point in the constructor for the class and debug your program.
NOTE: Is is normal for a program to create multiple logs files for different purposes and these might be the PrintStreams you are thinking of.
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();
}
}
what is the difference when I use buffer istead of console() for retriving the output from my code?
The Console class, as used by System.console() seems targeted to interactive character-based I/O, as provided by an actual console such as a cmd.exe window in Windows or a terminal in Unix-like systems. As such, the system console may not always be available, depending on the underlying OS and how the JVM was started.
On the other hand, Scanner works with any input stream, including files and the standard input. It is more flexible, but it does not provide some console-specific functionality that Console does, such as the ability to read text - usually passwords - without echoing it back to the console.
The Console class makes it easy to accept input from the command line, both echoed and unechoed. Unechoed means you will see some special character in your console while writing a text (ex. *, ? etc) like when you enter your password in facebook. :) Its format() method also makes it easy to write formatted output to the command line(like making a pyramid of *s or a formatted date and currency formats etc). It also helps to write test engines for unit testing. or you can use it to provide you a simple CLI (Command Line Interface) instead of a GUI (Graphical User Interface) in case you want to create a real simple and small application. And yes, it is also system dependent that means that you cannot always rely on your system to provide you a console instance.
Now about buffering, its actually a technique used in I/O (i.e. both input and output) when you are interacting with a stream (be it a character stream or byte stream, be it from a console or a socket or a file). Its basically used to speed up the I/O and save system resources by avoiding multiple call to read() and write() methods. It is suggested that you use it in almost every kind of I/O interaction.
I feel silly asking this but: how can I read a string from a console that is not input but has already been written to the console?
For instance, if I print a line to the console how can I read it after the fact? I know this is atypical.
Except in certain special circumstances, you can't, as Brad pointed out in the comments. As a justification, consider that when you send some text to the console (via standard output or standard error) to be printed, there's no guarantee that the text actually will be printed. Perhaps the user has redirected that output stream to /dev/null, in which case the text is gone for good. Or perhaps the text has scrolled out of view.
Basically, don't count on ever being able to access something that was sent to the console for output. If you need it, keep a copy in your program. And if you're trying to get at something that another program sent to the console, you need to use some sort of different arrangement like shared memory, sockets, or a fifo pipe.
Replace both System.in and System.out with your own streams and
try to create a pipe between System.in and System.out;
I am not sure that, whether it works or not;
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 :-)