Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all types of objects, data types, characters, files, etc to fully execute the I/O operations.
An I/O (Input/Output) stream in Java is a sequence of data that flows in and out of a program. Streams are used to read data from input sources (like files, keyboards, or network connections) and write data to output destinations (like files, displays, or network connections).
Key Concepts
Types of Streams:
- Input Streams: Used for reading data. Examples include FileInputStream, BufferedInputStream, and ObjectInputStream.
- Output Streams: Used for writing data. Examples include FileOutputStream, BufferedOutputStream, and ObjectOutputStream.
Byte Streams vs. Character Streams:
- Byte Streams: Handle raw binary data and are suitable for all types of I/O (e.g., images, audio). Classes include InputStream and OutputStream.
- Character Streams: Handle character data and are suitable for text files. They read and write characters, making them ideal for text processing. Classes include Reader and Writer.
Filtering Streams: Java provides filtering streams that allow you to read from or write to existing streams with additional processing. For example, BufferedInputStream adds buffering capabilities to an input stream, improving efficiency.
Serialization: Java supports serialization, which allows objects to be converted into a byte stream for storage or transmission. This is typically done using ObjectOutputStream for writing and ObjectInputStream for reading.
Exceptions: I/O operations can fail due to various reasons (e.g., file not found, permission issues). Java's I/O classes throw IOException for error handling.
Example
Here’s a simple example demonstrating reading from a file using an input stream and writing to a file using an output stream:
import java.io.*;
public class FileIOExample {
public static void main(String[] args) {
try {
// Writing to a file
FileOutputStream fos = new FileOutputStream("example.txt");
String data = "Hello, World!";
fos.write(data.getBytes());
fos.close();
// Reading from a file
FileInputStream fis = new FileInputStream("example.txt");
int content;
while ((content = fis.read()) != -1) {
System.out.print((char) content);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Summary
I/O streams in Java provide a powerful and flexible way to handle input and output operations, allowing for both simple and complex data processing. They enable interaction with various data sources and destinations, making them essential for file handling, network communication, and user input/output in applications.