Java’s I/O (Input/Output) system is robust and flexible, allowing programs to interact with various sources and destinations of data, including the console, files, and networks.
Thank you for reading this post, don't forget to subscribe!- The core I/O classes are found in the java.io package.
What is a Stream?
In Java, a stream is a continuous flow of data from a source to a destination.
There are two main types of streams:
- Input Streams: Read data from a source.
- Output Streams: Write data to a destination.
1.) Byte Streams: Handle raw bytes (e.g., images, audio, binary files).
- InputStream (abstract base class for byte input)
- OutputStream (abstract base class for byte output)
- Common concrete classes: FileInputStream, FileOutputStream, BufferedInputStream, BufferedOutputStream, DataInputStream, DataOutputStream.
2.) Character Streams: Handle characters (text data), which are more convenient for human-readable data as they handle character encodings.
- Reader (abstract base class for character input)
- Writer (abstract base class for character output)
- Common concrete classes: FileReader, FileWriter, BufferedReader, BufferedWriter, PrintWriter.
Common Interfaces:
- Closeable: Marks a resource that can be closed (e.g., streams). Used with try-with-resources.
- Flushable: Marks a destination that can be flushed (e.g., Writer to ensure data is written to the underlying device).
- Serializable: Used for object serialization (converting an object’s state into a byte stream for storage or transmission).
Example (Console I/O):
import java.util.Scanner;
public class ConsoleInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // System.in is an InputStream
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
}
}