Quiz 2

I/O Streams & Serialization

811 words
4 min read
Python Week 1: the first filter for runtime behavior
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

pseudo
Byte 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

java
import 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)

java
Student 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)

java
try (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

java
private 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

FeatureJavaPython
File readingBufferedReader, FileReaderopen(), read()
File writingPrintWriter, FileWriteropen(), write()
SerializationObjectOutputStream, Serializablepickle.dump(), pickle.load()
Binary I/OFileInputStream, FileOutputStreamopen(..., 'rb'), open(..., 'wb')
Resource mgmttry-with-resourceswith statement

7. Practice Questions

Q1: What does transient do?
Answer: transient marks 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: InvalidClassException is 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:
java
List<Student> students = new ArrayList<>();
// ... add students
oos.writeObject(students);  // Entire list is serialized
Q7: 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 via getSuppressed()). This prevents resource leaks. Q8: Can you serialize an object that has a non-serializable field?
Answer: Yes, if the field is marked transient, or you implement custom serialization (writeObject/readObject). If the field is not transient and not serializable, serialization throws NotSerializableException.

📐 Key Concepts

Stream TypeClassUse Case
Byte inputFileInputStreamBinary files (images, audio)
Byte outputFileOutputStreamWrite binary files
Char inputFileReader, BufferedReaderRead text files
Char outputFileWriter, PrintWriterWrite text files
Object outputObjectOutputStreamSerialize objects
Object inputObjectInputStreamDeserialize objects

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.