File I/O Overview
I/O stands for input and output
Java provides several APIs to perform input and output operations and all these APIs are bundled in a package called “java.io” package.
Input means reading data from a source
Reading data from a file
Reading data from keyboard
output means writing data to the destination.
Writing data to a file
Writing data to the output console
We get several scenarios in real time project where we need to use these I/O operations.
We use “streams” in java to perform I/O operations.
A stream is a sequence of data.
A program uses an input stream to read data from a source, one item at a time
A program uses an output stream to write data to a destination, one item at a time
Source and destination can be anything that holds, generates or consumes data
disk files,network socket,peripheral device etc.
Input stream and output stream class hierarchy
Frequently used method of input stream
This method Reads the next byte of data from the input stream.
The value byte is returned as an int in the range 0 to 255.
If no byte is available because the end of the stream has been reached, the value -1 is returned.
This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
This method returns an estimate number of bytes that can be read from the current input stream.
Returns 0 when it reaches the end of input stream.
This method Closes the input steam and releases any system resources associated with the stream.
Frequently used method of output stream
Writes the specified byte to this output stream.
The general contract for write is that one byte is written to the output stream.
- public abstract void write(int b)
- throws IOException
public abstract void write(int b) throws IOException
Writes b.length bytes from the specified byte array to this output stream
Flushes the output stream and forces any buffered output bytes to be written out.
Closes this output stream and releases any system resources associated with this stream.