I/O Streams & Serialization
811 words
4 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# I/O Streams & Serialization ## 🎯 Learning Objectives - Use byte streams (InputStream/OutputStream) and char streams (Reader/Writer) - Read/write text files with BufferedReader/PrintWriter - Serialize and deserialize objects with Serializable - Use try-with-resources for automatic stream closing ## 1. Stream Archi...

I/O Streams & Serialization
🎯 Learning Objectives
- Use byte streams (InputStream/OutputStream) and char streams (Reader/Writer)
- Read/write text files with BufferedReader/PrintWriter
- Serialize and deserialize objects with Serializable
- Use try-with-resources for automatic stream closing
1. Stream Architecture
pseudoByte Streams (binary data): InputStream → FileInputStream, BufferedInputStream, ObjectInputStream OutputStream → FileOutputStream, BufferedOutputStream, ObjectOutputStream Character Streams (text data): Reader → FileReader, BufferedReader, InputStreamReader Writer → FileWriter, PrintWriter, BufferedWriter
2. Reading/Writing Text Files
java// Reading (Java 7+ try-with-resources) try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); } // Writing try (PrintWriter writer = new PrintWriter(new FileWriter("output.txt"))) { writer.println("First line"); writer.println("Second line"); writer.printf("Formatted: %d + %d = %d%n", 2, 3, 5); } catch (IOException e) { System.err.println("Error writing file: " + e.getMessage()); }
3. Byte Streams — Binary Data
java// Copy file byte by byte try (FileInputStream in = new FileInputStream("source.jpg"); FileOutputStream out = new FileOutputStream("dest.jpg")) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } catch (IOException e) { System.err.println("Error copying file: " + e.getMessage()); }
4. Object Serialization
4.1 Making a Class Serializable
javaimport java.io.*; public class Student implements Serializable { private static final long serialVersionUID = 1L; // Version control private String name; private int rollNumber; private transient String password; // NOT serialized // Constructor, getters, setters... }
transient keyword: Marks fields that should NOT be serialized (e.g., passwords, cached values).
4.2 Writing Objects (Serialization)
javaStudent student = new Student("Alice", 101, "secret123"); try (ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("student.dat"))) { oos.writeObject(student); // Serialize entire object graph System.out.println("Object serialized"); } catch (IOException e) { System.err.println("Serialization failed: " + e); }
4.3 Reading Objects (Deserialization)
javatry (ObjectInputStream ois = new ObjectInputStream( new FileInputStream("student.dat"))) { Student student = (Student) ois.readObject(); // Cast required System.out.println("Name: " + student.getName()); System.out.println("Password: " + student.getPassword()); // null! (transient) } catch (IOException | ClassNotFoundException e) { System.err.println("Deserialization failed: " + e); }
5. serialVersionUID
javaprivate static final long serialVersionUID = 123456789L;
- Used during deserialization to verify the sender and receiver of a serialized object have loaded classes compatible with serialization
- If the class definition changed (different UID), deserialization throws
InvalidClassException - If not declared, JVM generates one (inconsistent across compilers)
6. Java vs Python: I/O
| Feature | Java | Python |
|---|---|---|
| File reading | BufferedReader, FileReader | open(), read() |
| File writing | PrintWriter, FileWriter | open(), write() |
| Serialization | ObjectOutputStream, Serializable | pickle.dump(), pickle.load() |
| Binary I/O | FileInputStream, FileOutputStream | open(..., 'rb'), open(..., 'wb') |
| Resource mgmt | try-with-resources | with statement |
7. Practice Questions
Q1: What doestransientdo?Answer:transientmarks a field that should not be serialized. During deserialization, transient fields get their default values (null for objects, 0 for primitives). Q2: Why use BufferedInputStream instead of FileInputStream directly?Answer: BufferedInputStream wraps FileInputStream with an internal buffer (default 8KB). Instead of reading one byte at a time (expensive OS calls), it reads large chunks, improving performance significantly for sequential access. Q3: What happens if serialVersionUID doesn't match during deserialization?Answer:InvalidClassExceptionis thrown. The JVM considers the class definitions incompatible and refuses to deserialize. Q4: Can static fields be serialized?Answer: No, static fields belong to the class, not the object. Serialization works on object state. Static fields are not serialized. Q5: What is the difference between FileReader and InputStreamReader?Answer: FileReader is a convenience class for reading character files (uses default charset). InputStreamReader is more general: it reads bytes and decodes them to characters using a specified charset. Q6: How do you serialize a collection?Answer: Most collection implementations (ArrayList, HashMap, etc.) already implement Serializable. Simply serialize the collection object directly:javaList<Student> students = new ArrayList<>(); // ... add students oos.writeObject(students); // Entire list is serializedQ7: What is the purpose of try-with-resources in I/O?Answer: Ensures each resource is closed at the end of the statement. Resources are closed in reverse order of declaration. If an exception occurs during close, it's suppressed (but accessible viagetSuppressed()). This prevents resource leaks. Q8: Can you serialize an object that has a non-serializable field?Answer: Yes, if the field is markedtransient, or you implement custom serialization (writeObject/readObject). If the field is not transient and not serializable, serialization throwsNotSerializableException.
📐 Key Concepts
| Stream Type | Class | Use Case |
|---|---|---|
| Byte input | FileInputStream | Binary files (images, audio) |
| Byte output | FileOutputStream | Write binary files |
| Char input | FileReader, BufferedReader | Read text files |
| Char output | FileWriter, PrintWriter | Write text files |
| Object output | ObjectOutputStream | Serialize objects |
| Object input | ObjectInputStream | Deserialize objects |
🔗 Cross-References
- Next: Streams API & Lambdas Join Discord Previous7.1 Exception HandlingNext8.1 Streams API & Lambdas