Java I/O
Java I/O (Input and Output) is used to process the input and
produce the output.
Java uses the concept of a stream to make I/O operation fast. The
java.io package contains all the classes required for input and
output operations.
We can perform file handling in Java by Java I/O API.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes.
It's called a stream because it is like a stream of water that continues to
flow.
In Java, 3 streams are created for us automatically. All these streams are
attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
OutputStream vs InputStream
OutputStream
Java application uses an output stream to write data to a
destination; it may be a file, an array, peripheral device or
socket.
InputStream
Java application uses an input stream to read data from a
source; it may be a file, an array, peripheral device or socket.
OutputStream class
OutputStream class is an abstract class. It is the
superclass of all classes representing an output
stream of bytes. An output stream accepts output
bytes and sends them to some sink.
Useful methods of OutputStream
Method Description
1) public void write(int)throws is used to write a byte to the current
IOException output stream.
2) public void write(byte[])throws is used to write an array of byte to the
IOException current output stream.
3) public void flush()throws
flushes the current output stream.
IOException
4) public void close()throws is used to close the current output
IOException stream.
InputStream class
InputStream class is an abstract class. It is the superclass
of all classes representing an input stream of bytes.
Useful methods of InputStream
Method Description
reads the next byte of data from the
1) public abstract int read()throws
input stream. It returns -1 at the end of
IOException
the file.
returns an estimate of the number of
2) public int available()throws
bytes that can be read from the current
IOException
input stream.
3) public void close()throws is used to close the current input
IOException stream.
Java FileOutputStream Class
Java FileOutputStream is an output stream used for
writing data to a file.
FileOutputStream class declaration
public class FileOutputStream extends OutputStream
Example
import java.io.FileOutputStream;
public class FileOutputStreamExample
{
public static void main(String args[])
{ try
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}
catch(Exception e){
System.out.println(e);
}
}
}