- What Is Java Stream? What Is The Input/output Stream?
- I/O Streams
- Java I/O | I/O Streams in Java
- Introduction to I/O Streams in Java
- What is Java IO?
- Input Streams
- Output Streams
- Error Streams
- Why We Need IO Streams in Java?
- Types of Streams in Java
- Input Stream
- InputStream Hierarchy
- Useful methods of InputStream
- Examples
What Is Java Stream? What Is The Input/output Stream?
In Java, the java.io package provides classes for working with input and output (I/O) operations. The package includes classes for reading from and writing to streams. A stream is a sequence of data that can be read from or written to various sources, such as files, network connections, or even other programs.
In this tutorial, we’ll cover the basics of using streams in Java, including input/output streams, and file I/O using the FileInputStream and FileOutputStream classes.
1. InputStream and OutputStream
The InputStream and OutputStream are abstract classes that represent the base for all input and output streams in Java. These classes provide methods for reading and writing bytes.
- InputStream provides methods like read() , available() , and close() .
- OutputStream provides methods like write() , flush() , and close() .
2. FileInputStream and FileOutputStream
FileInputStream and FileOutputStream are subclasses of InputStream and OutputStream used for reading from and writing to files.
Example: Reading from a file using FileInputStream
Create a file named «input.txt» with some text in it.
import java.io.FileInputStream; import java.io.IOException; public class Main < public static void main(String[] args) < try < FileInputStream fis = new FileInputStream("input.txt"); int data; while ((data = fis.read()) != -1) < System.out.print((char) data); >fis.close(); > catch (IOException e) < e.printStackTrace(); >> >
In this example, we create a FileInputStream object to read from the «input.txt» file. We then use the read() method to read each byte of data and print it as a character.
Example: Writing to a file using FileOutputStream
import java.io.FileOutputStream; import java.io.IOException; public class Main < public static void main(String[] args) < try < FileOutputStream fos = new FileOutputStream("output.txt"); String text = "This is a sample text."; fos.write(text.getBytes()); fos.close(); System.out.println("Text written to the file."); >catch (IOException e) < e.printStackTrace(); >> >
In this example, we create a FileOutputStream object to write to the «output.txt» file. We then use the write() method to write the bytes of a string to the file.
Note: Since Java 7, you can use try-with-resources to automatically close the streams. This is recommended as it helps prevent resource leaks.
Example of using try-with-resources:
import java.io.FileInputStream; import java.io.IOException; public class Main < public static void main(String[] args) < try (FileInputStream fis = new FileInputStream("input.txt")) < int data; while ((data = fis.read()) != -1) < System.out.print((char) data); >> catch (IOException e) < e.printStackTrace(); >> >
In this tutorial, we covered the basics of using streams in Java, including input/output streams and file I/O using the FileInputStream and FileOutputStream classes. These classes provide a foundation for working with file I/O in Java, but for more advanced use cases, consider using the java.nio package, which provides better performance and additional features.
Professional provider of PDF & Microsoft Word and Excel document editing and modifying solutions, available for ASP.NET AJAX, Silverlight, Windows Forms as well as WPF. We are dedicated to provide powerful & profession PDF/Word/Excel controls.
I/O Streams
An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.
Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.
No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data. A program uses an input stream to read data from a source, one item at a time:
Reading information into a program.
A program uses an output stream to write data to a destination, one item at time:
Writing information from a program.
In this lesson, we’ll see streams that can handle all kinds of data, from primitive values to advanced objects.
The data source and data destination pictured above can be anything that holds, generates, or consumes data. Obviously this includes disk files, but a source or destination can also be another program, a peripheral device, a network socket, or an array.
In the next section, we’ll use the most basic kind of streams, byte streams, to demonstrate the common operations of Stream I/O. For sample input, we’ll use the example file xanadu.txt , which contains the following verse:
In Xanadu did Kubla Khan A stately pleasure-dome decree: Where Alph, the sacred river, ran Through caverns measureless to man Down to a sunless sea.
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 it stores data. Take an example of a river stream, where water flows from source to destination. Similarly, these are data streams; data flows through one point to another.
To handle these sequences, we introduce a term called IO streams .
The java.io package helps the user to perform all types of 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 source as input and 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 input and output streams used to read and write data to files or other input and output sources.
There are 3 categories of classes in java.io package:
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 input source consists of data that needs to be read in order to extract information from it. Input Streams help us to read data from the input source. It is an abstract class that provides a programming interface for all input streams.
Input streams are opened implicitly as soon as it is created. To close the input stream, we use a close() method on the source object.
Output Streams
The output of the executed program has to be stored in a file for further use. Output streams help us to write data to a output source(may be file). Similarly like input streams output streams are also abstract classes that provides a programming interface for all output streams.
The output stream is opened as soon as it is created and explicitly closed by using the close() method.
Error Streams
Error streams are the same as output streams. In some ide’s error is displayed in different colors (other than the color of output color). It gives output on the console the same as output streams.
Why We Need IO Streams in Java?
In day-to-day work, we do not enter the input into the programs manually. Also, the result of the program needs to be stored somewhere for further use.
So, IO streams in Java provide us with input and output streams that help us to extract data from the files and write the data into the files. Normally, we can create, delete, and edit files using Java.io.
In short, all the file manipulation is done using Java IO streams . Java IO streams 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, reading data from files or from 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 helps to return the data of the next byte in the input stream. The value returned is between 0 to 255 . If no byte is read, the code returns -1 , which indicates the end of the file.
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 system resources associated with it.
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 to read before the mark position gets invalid.
5. public boolean markSupported()
It tells whether the mark() and reset() method is supported in a particular input stream. It returns true if the mark and reset methods are supported by the particular input stream or else return 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. It returns the total number of bytes stored in the buffer . Here the “off” is 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: