Java I/O Streams
💻 Java I/O Streams
In Java, I/O (Input/Output) Streams are used to read data from a source or write data to a destination.
-
InputStream → Read data (input)
-
OutputStream → Write data (output)
Streams handle byte-level or character-level data.
🧩 Types of Streams
1️⃣ Based on Data Type
| Stream Type | Description |
|---|---|
| Byte Streams | Read/write binary data (images, files, audio) |
| Character Streams | Read/write text data (characters, strings) |
2️⃣ Based on Direction
| Direction | Class/Interface |
|---|---|
| Input | InputStream, Reader |
| Output | OutputStream, Writer |
✅ 1. Byte Streams (Binary Data)
-
InputStream → Read bytes
-
OutputStream → Write bytes
Example: Reading a File Using FileInputStream
Example: Writing a File Using FileOutputStream
✅ 2. Character Streams (Text Data)
-
Reader → Read characters
-
Writer → Write characters
Example: Reading Using FileReader
Example: Writing Using FileWriter
✅ 3. Buffered Streams (Efficient I/O)
-
Wrap streams to buffer data → improves performance
-
Classes:
BufferedReader,BufferedWriter,BufferedInputStream,BufferedOutputStream
Example: BufferedReader
✅ 4. Data Streams (Read/Write Primitive Data)
-
DataInputStream→ Read primitive types (int, double, etc.) -
DataOutputStream→ Write primitive types
🧠 Summary Table
| Stream Type | Class Example | Use Case |
|---|---|---|
| Byte Input | FileInputStream |
Read binary files |
| Byte Output | FileOutputStream |
Write binary files |
| Character Input | FileReader |
Read text files |
| Character Output | FileWriter |
Write text files |
| Buffered | BufferedReader/BufferedWriter |
Efficient text I/O |
| Data Streams | DataInputStream/DataOutputStream |
Read/write primitives |
Best Practices
-
Always close streams (use try-with-resources).
-
Use Buffered streams for better performance with large files.
-
Choose byte streams for binary data and character streams for text.
