Published by: Dikshya
Published date: 25 Jun 2023
Input Stream:
An Input Stream represents a sequence of data being read from a source. It provides methods to retrieve data from the source in a sequential manner. You can read individual bytes or characters, as well as larger chunks of data, from an input stream.
Output Stream:
An Output Stream represents a sequence of data being written to a destination. It provides methods to write data to the destination in a sequential manner. You can write individual bytes or characters, as well as larger chunks of data, to an output stream.
The Input Stream and Output Stream concepts are often used together to facilitate input/output operations in a program. For example, you might read data from an input stream and process it, then write the processed data to an output stream.
File Input Stream:
A File Input Stream is an input stream that allows reading data from a file. It provides methods to read data from the file in a sequential manner. With a file input stream, you can read individual bytes or characters, as well as larger chunks of data, from a file.
File Output Stream:
A File Output Stream is an output stream that allows writing data to a file. It provides methods to write data to the file in a sequential manner. Using a file output stream, you can write individual bytes or characters, as well as larger chunks of data, to a file.
Here's an example in Java that demonstrates the usage of File Input Stream and File Output Stream:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileIOExample {
public static void main(String[] args) {
try {
// File Input Stream
FileInputStream fileInputStream = new FileInputStream("input.txt");
int data;
while ((data = fileInputStream.read()) != -1) {
// Process the data
System.out.print((char) data);
}
fileInputStream.close();
// File Output Stream
FileOutputStream fileOutputStream = new FileOutputStream("output.txt");
String text = "Hello, World!";
byte[] bytes = text.getBytes();
fileOutputStream.write(bytes);
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above example, the File Input Stream is used to read data from the "input.txt" file, and the File Output Stream is used to write the string "Hello, World!" to the "output.txt" file.