Java I/O (Input/Output) is a collection of classes and streams in the java.io package that handle reading data from sources (like files, keyboard, or network) and writing data to destinations (like files, console or sockets). It provides both byte and character streams to support all types of data.
Flow from Source to Destination
Default/Standard Streams in Java
Before exploring various input and output streams, let's look at 3 most commonly used default streams that Java has provided:
Default Stream
System.in: This is the standard input stream that is used to read characters from the keyboard or any other standard input device.
System.out: This is the standard output stream that is used to produce the result of a program on an output device like the computer screen.
System.err: This is the standard error stream that is used to display error messages separately from normal output.
Functions used with Default Streams:
1. System.in
System.in is an InputStream, so it provides methods from the InputStream class. Commonly used ones are:
int read(): reads one byte of data.
int read(byte[] b): reads bytes into an array.
int read(byte[] b, int off, int len): reads bytes into part of an array.
void close(): closes the input stream.
int available(): returns the number of bytes that can be read without blocking.
Usually, System.in is wrapped with classes like Scanner or BufferedReader for easier input handling.
Example:
Java
importjava.io.IOException;publicclassSystemInExample{publicstaticvoidmain(String[]args)throwsIOException{System.out.println("Enter a character:");// Reads a single byte from System.inintdata=System.in.read();// Print the character and its ASCII valueSystem.out.println("You entered: "+(char)data);System.out.println("ASCII Value: "+data);}}
Output:
Output
2. System.out
print(): This Java method displays text on the console, keeping the cursor at the end of the printed text so the next output continues from the same line.
Syntax:
System.out.print(parameter);
Example:
Java
importjava.io.*;classGeeks{publicstaticvoidmain(String[]args){// using print() all are printed in the same lineSystem.out.print("GfG! ");System.out.print("GfG! ");System.out.print("GfG! ");}}
Output
GfG! GfG! GfG!
println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line.
Syntax:
System.out.println(parameter);
Example:
Java
importjava.io.*;classGeeks{publicstaticvoidmain(String[]args){// using println() all are printed in the different lineSystem.out.println("GfG! ");System.out.println("GfG! ");System.out.println("GfG! ");}}
Output
GfG!
GfG!
GfG!
printf(): The printf() method in Java is used for formatted output and can take multiple arguments, making it more flexible than print() or println().
Example:
Java
classGeeks{publicstaticvoidmain(String[]args){intx=100;// Printing a simple integerSystem.out.printf("Printing simple integer: x = %d%n",x);// Printing a floating-point number with precisionSystem.out.printf("Formatted with precision: PI = %.2f%n",Math.PI);floatn=5.2f;// Formatting a float to 4 decimal placesSystem.out.printf("Formatted to specific width: n = %.4f%n",n);n=2324435.3f;// Right-aligning and formatting a float to 20-character widthSystem.out.printf("Formatted to right margin: n = %20.4f%n",n);}}
Output
Printing simple integer: x = 100
Formatted with precision: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500
3. System.err
It is used to display the error messages. It works similarly to System.out with print(), println(), and printf() methods.
Example: Java Program demonstrating System.err
Java
publicclassGeeks{publicstaticvoidmain(String[]args){// Using print()System.err.print("This is an error message using print().\n");// Using println()System.err.println("This is another error message using println().");//Using printf()System.err.printf("Error code: %d, Message: %s%n",404,"Not Found");}}
Output:
Output
Types of Streams
Depending on the type of operations, streams can be divided into two primary classes:
1. Input Stream: These streams are used to read data that must be taken as an input from a source array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream etc.
InputStream
2. Output Stream: These streams are used to write data as outputs into an array or file or any output peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc.
Types of Streams Depending on type of data (byte vs character
Depending on the types of file, Streams can be divided into two primary classes which can be further divided into other classes as can be seen through the diagram below followed by the explanations.
Classification
1. ByteStream:
Byte streams in Java are used to perform input and output of 8-bit bytes. They are suitable for handling raw binary data such as images, audio, and video, using classes like InputStream and OutputStream.
This is an abstract class that describes stream output.
Example: Java Program illustrating the Byte Stream to copy contents of one file to another file.
Java
importjava.io.*;publicclassGeeks{publicstaticvoidmain(String[]args)throwsIOException{FileInputStreamsourceStream=null;FileOutputStreamtargetStream=null;try{sourceStream=newFileInputStream("sourcefile.txt");targetStream=newFileOutputStream("targetfile.txt");// Reading source file and writing content to target file byte by byteinttemp;while((temp=sourceStream.read())!=-1)targetStream.write((byte)temp);}finally{if(sourceStream!=null)sourceStream.close();if(targetStream!=null)targetStream.close();}}}
Output:
Shows contents of file test.txt
2. CharacterStream:
Character streams in Java are used to perform input and output of 16-bit Unicode characters. They are best suited for handling text data, using classes like Reader and Writer which automatically handle character encoding and decoding.
Here is the list of various CharacterStream Classes:
This is used to output stream that writes to file.
Example:
Java
importjava.io.*;publicclassGeeks{publicstaticvoidmain(String[]args)throwsIOException{FileReadersourceStream=null;try{sourceStream=newFileReader("test.txt");// Reading sourcefile character by character.inttemp;while((temp=sourceStream.read())!=-1)System.out.println((char)temp);}finally{// Closing stream as no longer in useif(sourceStream!=null)sourceStream.close();}}}
You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.