Java Input/Output
The java.io package contains all the class needs to perform input and output (I/O) operation in Java.
Every Java programs perform I/O through streams.

Stream
A stream is defined as a sequence of data. There are two types of streams
InputStream
To read data from a source which is called an inputstream.
OutputStream
Writing data to a destination which is called an OutputStream.

Byte Streams
Java byte streams are used for handling input and output of bytes.
The most frequently used classes in byte stream are FileInputStream and FileOutputStream.
Example:
import java.io.*;
public class ByteStream{
public static void main(String args[]) throws IOException {
try {
FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("output.txt");
int count;
while ((count = in.read()) != -1) {
out.write(count);
}
System.out.println("Success");
}catch(Exception e){
System.out.println(e);
}
finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}
}
Success
Input.txt
Hi How r u?
Character Streams
Java character streams are used for handling input and output of characters.
The most frequently used classes in character stream are FileReader and FileWriter.
Example:
import java.io.*;
public class CharacterStream{
public static void main(String args[]) throws IOException {
try {
FileReader in = new FileReader("input.txt");
FileWriter out = new FileWriter("output.txt");
int count;
while ((count = in.read()) != -1) {
out.write(count);
}
System.out.println("Success");
}catch(Exception e){
System.out.println(e);
}
finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}
}
Output
Success
Input.txt
Hi How r u?
The Predefined Streams
There are three predefined streams.
System.out - standard output stream, which is the console by default.
System.in - standard input stream, which is the keyboard by default.
System.err - standard error stream, which is the console by default.
OutputStream class
OutputStream class is an abstract class. The OutputStream is used for writing data to a destination.
OutputStream Hierarchy

InputStream class
InputStream class is an abstract class. The InputStream is used to read data from a source.
InputStream Hierarchy

Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com