Java I/O | I/O Streams in Java
The java.io package is used to handle input and output operations. Java IO has various classes that handle input and output sources. A stream is a sequence of data.
Java input stream classes can be used to read data from input sources such as keyboard or a file. Similarly output stream classes can be used to write data on a display or a file again.
We can also perform File Handling using Java IO API.
Introduction to I/O Streams in Java
Before understanding IO streams, let us discuss streams. A Stream is also a sequence of data. It is neither a data structure nor a store of data. For example, a river stream is where water flows from source to destination. Similarly, these are data streams; data flows through one point to another.
We introduce a term called IO streamsto handle these sequences.
The java.io package helps the user perform all input-output operations. Java IO package is primarily focused on input-output files, network streams, internal memory buffers, etc. Data is read and written from Java IO's InputStream and OutputStream classes.
In other words, IO streams in Java help to read the data from an input stream, such as a file and write the data into an output stream, such as the standard display or a file again. It represents the source as input and the destination as output. It can handle all types of data, from primitive values to advanced objects.
What is Java IO?
The java.io package consists of output and input streams used to write and read data to files or other output and input sources.
There are 3 categories of classes in java.io package:
- Input Streams.
- Output Streams.
- Error Streams.
Java supports three streams that are automatically attached with the console.
- System.out: Standard output stream
- System.in: Standard input stream
- System.err: Standard error stream
Input Streams
As we know, an input source consists of data that needs to be read in order to extract information from it. Input Streams help us read data from the input source. They are an abstract class that provides a programming interface for all input streams.
Input streams are opened implicitly as soon as they are created. We use a close() method on the source object to close the input stream.
Output Streams
The executed program's output must be stored in a file for further use. Output streams help us write data to an output source(such as a file). Similarly to input streams, output streams are abstract classes that provide a programming interface for all output streams.
The output stream is opened as soon as it is created and explicitly closed using the "close() "method.
Error Streams
Error streams are the same as output streams. In some ide’s, the error is displayed in different colors (other than the color of the output color). It gives output on the console the same as output streams.
Why We Need IO Streams in Java?
In daily work, we do not enter input into programs manually. Also, the program's result needs to be stored somewhere for further use.
So, Java IO streams provide input and output streams that help us extract data from files and write the data into them. Normally, we can create, delete, and edit files using Java.io.
In short, all file manipulation is done using "Java IO streams, " which also handle user input functionality.
Types of Streams in Java
Depending on the types of operations, streams are divided into 2 primary classes.
Input Stream
It is an abstract superclass of the java.io package and is used to read the data from an input source. In other words, it means reading data from files, using a keyboard, etc. We can create an object of the input stream class using the new keyword. The input stream class has several types of constructors.
The following code takes the file name as a string, to read the data stored in the file.
InputStream Hierarchy
Useful methods of InputStream
1. public abstract int read() throws IOException
The method above returns the data of the next byte in the input stream. The value returned is between 0and 255. If no byte is read, the code returns -1, indicating the file's end.
2. public int available() throws IOException
The method above returns the number of bytes that can be read from the input stream.
3. public void close() throws IOException
The method above closes the current input stream and releases any associated system resources.
4. public void mark(int readlimit)
It marks the current position in the input stream. The readlimit argument tells the input stream to read that many bytes before the mark position becomes invalid.
5. public boolean markSupported()
It tells whether a particular input stream supports the mark() and reset() method. It returns true if the particular input stream supports the mark and reset methods or returns false.
6. public int read(byte[ ] b) throws IOException
The method above reads the bytes from the input stream and stores every byte in the buffer array. It returns the total number of bytes stored in the buffer array. If there is no byte in the input stream, it returns -1 as the stream is at the end of the file.
7. public int read(byte[ ] b , int off , len) throws IOException
It reads up to len bytes of data from the input stream and returns the total number of bytes stored in the buffer. Here, the “off” is the start offset in buffer array b where the data is written, and the “len” represents the maximum number of bytes to read.
8. public void reset() throws IOException
It repositions the stream to the last called mark position. The reset method does nothing for input stream class except throwing an exception.
9. public long skip(long n) throws IOException
This method discards n bytes of data from the input stream.
Examples
- In the below example, we will use FileInputStream class to read the input file: input.txt.
- Create a file input.txt and place it in the same directory as Main.java
- Let us suppose input.txt contains the following content:
Code:
Output:
- In the below example, we will use BufferedInputStream class to read the file.
Code:
Output:
- In the below example, we will use the ByteArrayInputStream class to read the file.
Code:
Output:
Output Stream
It is an abstract superclass of the java.io package that writes data to an output resource, which is, in other words, writing the data into files. We can create an object of the output stream class using the new keyword. The output stream class has several types of constructors.
OutputStream Hierarchy
Useful methods of OutputStream
1. public void close() throws IOException
This method closes the current output stream and releases any associated system resources. The closed stream cannot be reopened, and operations cannot be performed on it.
2. public void flush() throws IOException
It flushes the current output stream and forces any buffered output to be written out.
3. Public void write(byte[ ] b) throws IOException
This method writes the b.length bytes from the specified byte array to the output stream.
4. Public void write(byte[ ] b ,int off ,int len) throws IOException
It writes up to len bytes of data for the output stream. Here, the “off” is the start offset in buffer array b, and the “len” represents the maximum number of bytes to be written in the output stream.
5. Public abstract void write(int b) throws IOException
The method above writes the specific bytes to the output stream. It does not return a value.
Some methods that are inherited from class java.lang.Object. These methods are used for both input stream and output stream purposes.
Example: clone, equals, finalise, getclass, hashCode, notify, notifyAll, toString, wait.
Examples
- In the example below, we will use the FileOutputStream class to read the file.
Code:
Output:
The output.txt file will contain the following text:
- In the example below, we will use the BufferedOutputStream class to read the file.
Code:
Output:
The output.txt file will contain the following text:
- In the below example, we will use the ByteArrayOutputStream class to read the file.
Code:
Output:
The output.txt`` file will contain the following text:
Conclusion
- Java has three main types of IO streams.
- Input Streams
- Output Streams
- Error Streams
- Input Stream and Output Stream are abstract superclasses of the java.io package.
- Input and Output Streams are used to read data from input sources (such as Standard Input) and write data into output sources (such as files and consoles).