Java error output to file

Standard Input, Output, and Error in Java



When writing command line applications in Java, you may want to prompt the user for input or a password, process a file, or pipe the output of another process through your application. This tutorial will walk through the process of using standard input, output, and error in Java.

If you are not familiar with standard streams, and file descriptors 0, 1, and 2, read up on For this tutorial, Java 1.8 JDK is used.

One thing many developers overlook is the ability to write to standard output and standard error as different streams. If your application needs to print debug or other information while also outputting clean results, you should separate the output between standard output and standard error.

Standard output should be reserved only for your clean output that can be piped to a file or another process without error messages. Standard error should be used for errors, warnings, debug information, and anything you want the user to see, but you don’t want to be included as part of the final output of the program. For example, let’s say you have an application that outputs a series of strings that you pipe through to grep like this:

In use cases like this, you may want to print an error or a warning to user that should not be included in the output to the next process (grep in this example). This is a good situation where you would continue piping standard output to the next process in the chain, but stderr would still print to the terminal for the user to see without being processed by grep.

By default, standard output and standard error both print to the terminal, so it’s hard to distinguish them, but it becomes painfully obvious when you try to pipe output to another application or a file.

Java represents the standard streams with the following objects that can be read from and written to. Rememeber, these streams are treated just like files, even though the input may come from a keyboard, a file, or another process, and the output may go to the screen, a file, or another process.

You may already be familiar with System.out.println, a common function used to write data to standard output. For many developers, that is as far as they have explored the standard streams though. Let’s dive in and look at what we can do.

Reading binary data from standard input

Since is just a regular InputStream we can read directly from it using You can see what methods are available for an InputStream using the official documentation at InputStreams don’t have a huge selection of methods, but they get the simple jobs done. This next example demonstrates some basic operations by checking how many bytes are available, and then reading a single byte, followed by reading in to a buffer.

You can run it from the command line by itself and enter a string from the keyboard, or you can feed the program a file like this:

While I describe this technique as reading binary data, it applies equally to text input, considering text input is still binary input. However, if you want to read simple text, I describe a better technique in the next section using a Scanner. I recommend using this technique when you are working with binary files.

Prompting user for input

If you are writing an interactive application and you want to prompt to user to input some values, you can create a Scanner object that wraps A Scanner provides all kinds of convenient methods for reading an input stream. Instead of having to read one byte at a time and process everything ourself, we can have it find strings, integers, and other data one element at a time. By default it will use spaces and newline characters as separators when searching for elements, but you can modify that to be a comma if you are using a CSV, or any other kind of delimiter.

Читайте также:  Sdbus internal error windows 10 как исправить

There are also next* methods for the various data types. For example, nextByte(), nextBoolean(), nextBigDecimal(), etc. Refer to the Scanner documentation for more details.

Prompting user for a password

If you want to prompt the user for a password or other sensitive information, you may not want to echo the keys that the user is pressing on screen. Since Java 1.6, there has been a class with a readPassword() method that does exactly this. You can get the current console from System object using System.console().

It’s worth noting that the Constole class has other methods similar to the ones we already saw. For example, Console has a readLine() method, and a printf() method, but that’s about it. It is not as flexible as using a Scanner for input. The only thing it really offers is the convenient readPassword() method.

Reading standard input line-by-line

If you have a file being piped in to your application, you may want to continue processing every line as long as their is data. To do this you can utilize the Scanner described in the previous section to read line-by-line. This program will read line after line until it reaches an end of file (EOF) and print out the line it sees. It behaves similar to cat in Linux and type in Windows.

Writing to standard output

While we’re talking about streams, most people already know how to print out to standard output using System.out.println(), but there are also other methods. For example, you can use System.out.print() to print out content without creating a newline at the end. You can also use System.out.printf() to print C-style format strings.

Standard out in Java, System.out is a PrintStream object, which is a subclass of OutputStream. The Java 8 documentation for a PrintStream is available at

Writing to standard error

The standard error stream, System.err is a PrintStream just like System.out, so it has all of the same methods available. Everything you saw in the previous example regarding System.out can be repeated with System.err.

Running this example, the error output will likely go to your terminal output, and look just like standard output but it is being treated differently. Refer to the section below with examples of redirecting and piping the output and error streams separately.

How to redirect output

As mentioned earlier, you can separate the standard output and standard error streams, even though they are both printed out together to the terminal by default. You can also redirect one stream to another.

It is also possible to pipe the output of your program directly in to another program. This is done using the pipe character instead of the angle bracket.

How to redirect input

Another option is to use the output of another program as the input. This is called piping and is the same example we saw just a moment ago when redirecting output through a pipe, except output program is on the receiving end this time.

Читайте также:  Failed with error 317


With this information, you should comfortably be able to manipulate the input, output, and error streams of your program to suit your needs. Take advantage of the redirection and concurrency the operating system provides when piping output through multiple programs and be a good citizen in the ecosystem by using the standard streams properly.


How to get Exception log from a console and write it to external file in java?

There are several logging frame works available to log your data in to files. You can also define your own method.

Example − Using I/O package

Following Java program has an array storing 5 integer values, we are letting the user to choose two elements from the array (indices of the elements) and performing division between them. We are wrapping this code in try block with three catch blocks catching ArithmeticException, InputMismatchException and, ArrayIndexOutOfBoundsException. In each of them we are invoking the writeToFile() method.

This method accepts an exception object, and appends it to a file using the write() method of the Files class.


Output 1

Output 2

Output 3


Logging exceptions to a file using log4j

Following is an example which logs exceptions into a file using the logger library log4j.



Following Java program has an array storing 5 integer values, we are letting the user to choose two elements from the array (indices of the elements) and performing division between them. We are wrapping this code in try block with three catch blocks catching ArithmeticException, InputMismatchException and, ArrayIndexOutOfBoundsException. In each of them we are invoking the writeToFile() method.

This method accepts an exception object, and appends it to a file using the write() method of the Files class.


Java error output to file

In java the three main Streams stdin (standard input) , stdout (standard output) and stderr (standard output error) are handled by default by, Sytem.out and System.err respectively. Sometimes we may need to change the output according to our needs, this can be done in many ways such us using the OS to tell what stream we need to use or using java to set what streams we want to be used.

In these examples is shown how to deal with these streams in different sceenarios.

Redirecting streams to file from console in Unix

java MyExample > output.log 2>error.log

Redirecting Output Streams to Files

This example redirects both output streams to 2 different files. It produces an ArithmeticException dividing by 0 and the error trace will be stored in the stderr.log. The results won’t be shown in the console.

Redirecting Output Error Stream to the Standard Out Stream.

Redirecting Output Streams to Files and Printing the result in the console.

In this example a «proxy» class I used, so that every time the print or println methods are called its output will be printed by the console and also stored the specified files.

* This example appends traces to the existing file change new FileOutputStream(FilePath,true) for new FileOutputStream(FilePath) to create a new file each time.

Redirecting Output Streams in Log4J

This example prints all the traces ment for the standard outputs to the LOG4J files, so you can make sure that all traces are there.


How To Write Console Output To Text File In Java

The java.lang.System‘s out and err objects are used to write text data to the standard output stream and standard error stream. The default output stream is the command-line console. But the java.lang.System class also provides a method for you to redirect the standard output stream to other destinations such as file stream. With this, you can log text data to a log file in your java program.

Читайте также:  Mysql apt config error

1. Redirect Java System Output Stream Methods.

  1. The java.lang.System class provides the below methods to set standard output stream to custom stream.
  2. setOut(PrintStream ps): Set standard data output to a specified print stream such as a file stream.
  3. setErr(PrintStream ps): Set standard error output to a specified print stream such as a file stream.
  4. setIn(InputStream is): Set standard input stream to a custom input stream.

2. Redirect Java Out Error Stream Examples.

  1. Below are the steps of redirecting the output stream to the file stream.
  2. Create a file output print stream.
  3. Call System.setOut method to set above PrintStream as the new standard output stream.
  4. Call System.out.println to write text data to the file.

3. Write Console Output To Text File In Java Examples.

  1. Below is the full example source code.
  2. After executing the above code, you can see two files out.txt and err.txt are generated under the current java class execution folder.
  3. Below is another method to write user input in the command line console to a text file in java.

4. Why My Java Code Can Not Write Console Output To A Local Log Text File.

4.1 Question.

  1. I am new to java programming. And my java program generates a lot of log output text on the console screen using the method system.out.println() (2022/05/24).
  2. I want to save the above log text output to a log file instead of printing them on the console.
  3. Below is an example java source code, but it does not work as expected when I run it. Can anyone give me some suggestions? Thanks a lot.

4.2 Answer1.

  1. If you want to print the system standard output from the default console screen to a special file, you should change your java source code as below.
  2. The code System.setOut(pw) is very important, it will direct all your system.out.printiln() method printed text to the PrintWriter object. Then all those texts will be written to the PrintWriter wrapped text file.
  3. The above code will print text to the custom text file, but it will truncate the file when you print new text to the file.
  4. If you want to append the new text to the existing text file, you can set the append parameter to true to achieve this like the below source code.

1 thought on “How To Write Console Output To Text File In Java”

I have an existing java class which contains a lot of System.out.println() method to print text to the standard output console. But when the java class execute, I need the log text write to a file instead of writing to java standard output console. And I searched out this article. But it is difficult to update my old java class because there are too many System.out.println() lines, so I google out below method can also achieve this. In a terminal and run the command java Yout-Class-Name >> out.txt. Then it will print all the output text generated by the System.out.println() method to the text file.

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Оцените статью