What is System.out exactly? - java

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

Related

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

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

Checking to see where a function was called in Java

I'm working on some software that reads from a file system using a specific inputstream reader. This class has a function called read() which is used in some driver program to read files. I want to find out the location/source file for the driver program. If I only know where read() is implemented how can I find where it is used?
You can run this command on the top-level directory of the project to find where read() is used:
grep -n --recursive " read(" *
This will recursively search all the files for the string " read(" and print out which file it is in, as well as the line number.
Unfortunately, knowing where read() is implemented won't directly tell you where it is used. The implementation of a method is not dependent on where it is used, that's the other way around. If it were dependent, every single library in the Javadocs would have information about all the obscure programs that used such a library.
Assuming you can modify read() you might get a stack trace. Either throw an unchecked exception or do something like
StackTraceElement[] st = Thread.currentThread().getStackTrace();
System.out.println(Arrays.toString(st));

Is there any differnce between buffer and console to make use....

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.

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 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