In this section we will discuss about the Command Line Java IO Standard Error.
Command Line Standard Error In Java
In this section we will discuss about the Command Line Java IO Standard Error.
System.out and System.err both are for Standard output but, System.err separates the error output. System.err is provided by Java for printing of error messages.
System.err
In System.err, err is a public static final field defined as an object of PrintStream that specifies a standard error output stream is open and ready for accepting output data. These output data can be displayed output at the console, file or any other output destination depends upon the user or host environment. So, with the System.err we can use methods of PrintStream (discussed in the example given below).
public static final PrintStream err
Example
Here I am giving a simple example which will demonstrate about how Standard Error can be printed. In this example I have created a Java class named JavaSystemErrExample.java. In this class I have tried to take the input of file name at console and then read the content of that file. But in case if you will entered the file name incorrect or if the file doesn't existed in the specified directory then an error message will be printed. To print this error message I have used the Standard Error accessing i.e. System.err
Source Code
JavaSystemErrExample.java
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class JavaSystemErrExample { public static void main(String[] args) throws Exception { BufferedReader br = null; FileInputStream fis = null; String str; try{ br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter File Name: "); str = br.readLine(); File file = new File(str); fis = new FileInputStream(file); int r; while((r = fis.read()) != -1) { System.out.print((char)r); } } catch(IOException ioe) { System.err.println("File Doesn't Existed Into The Specified Directory"); } } }
Output
Execute this example two times.
1. In first time execute this example and provide the file name (available in the specified directory) as I given below then the contents of file will be read as follows
2. But, When you will give give the file name wrong then an error message will be displayed.