Phase 13
File Handling, java.io & Modern java.nio.file
📂 Module 1... \\ FileHandling_Demos & Module 2 \\ 01_Java11_Demos
13.1 java.io vs java.nio, Serialization & Files API
📖 Cay S. Horstmann • Core Java Volume II — Chapter 2 & Chapter 3 ("Input/Output & Object Serialization")
“NIO.2 provides robust non-blocking file manipulation using Path and Files. For persistence, object serialization transforms object graphs into byte streams. Sensitive fields must be marked transient.”
- BigDecimal RuleNever use double for currency! Always use new BigDecimal("0.1") with String constructor.
⚡ Pro-Tip: The transient Security Barrier
Mark passwords and secret tokens with transient. Serialization skips them completely, protecting against data leakage.
💡 Real-World Analogy: Classic java.io vs Modern java.nio
• Classic java.io (Sipping through a straw): Stream-oriented. You read byte-by-byte or line-by-line. While waiting for data, your thread is completely blocked and frozen.
• Modern java.nio (Freight Train Cargo Containers): Buffer and Channel oriented. You load large blocks of data into memory buffers directly with zero-copy kernel transfers. Highly scalable for high-concurrency web servers.
• Modern java.nio (Freight Train Cargo Containers): Buffer and Channel oriented. You load large blocks of data into memory buffers directly with zero-copy kernel transfers. Highly scalable for high-concurrency web servers.
📂 Module 2.../File_Additions.java — Modern 1-Line File Operations
package com.accenture.ltt.zeleven;
import java.nio.file.*;
import java.io.IOException;
public class File_Additions {
public static void main(String[] args) throws IOException {
Path path = Path.of("orders.log");
// Modern Java 11 Files API: 1 line write!
Files.writeString(path, "ORDER_PLACED: 1002 | STATUS: APPROVED");
// Modern Java 11 Files API: 1 line read!
String content = Files.readString(path);
System.out.println("Log Content: " + content);
// Cleanup
Files.deleteIfExists(path);
}
}
👁 Modern java.nio.file.Files API (Java 11+) Breakdown
-
Files.writeString()
Line 8: One atomic method call handles file creation, character encoding (UTF-8 by default), stream buffering, and guaranteed resource closing. Replaces 15 lines of legacy
FileWriterboilerplate. -
Files.readString()
Line 11: Reads an entire file directly into a
java.lang.Stringin a single line. Ideal for loading configuration files, templates, and certificates. -
Path.of()
Introduced in Java 11 as a convenient alias for
Paths.get(). Represents an immutable, hierarchical, platform-independent file system path.
📂 SerializationTransientDemo.java — Java Serialization & transient
import java.io.*;
public class SerializationTransientDemo {
static class UserSession implements Serializable {
private static final long serialVersionUID = 1L; // Guards against class version mismatch!
String username;
transient String passwordHash; // TRANSIENT: Excluded from serialization! Never written to disk!
UserSession(String username, String passwordHash) {
this.username = username;
this.passwordHash = passwordHash;
}
}
public static void main(String[] args) throws Exception {
UserSession session = new UserSession("admin", "super_secret_hash_999");
// 1. Serialization (Object -> Byte Stream)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(session);
}
// 2. Deserialization (Byte Stream -> Object)
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
UserSession restored = (UserSession) ois.readObject();
System.out.println("Restored Username: " + restored.username);
System.out.println("Restored Password (transient): " + restored.passwordHash); // Prints null! Safe!
}
}
}
👁 Java Serialization, serialVersionUID & the transient Keyword
- Serializable Interface A marker interface (0 methods) that signals to the JVM that the class's object graph can be flattened into a binary byte stream for disk storage or network transmission.
-
serialVersionUID Guard
Line 4: A unique 64-bit version identifier. If you modify class fields later without declaring
serialVersionUID, the compiler calculates a new hash and deserializing old saved files crashes withInvalidClassException! -
The transient Keyword
Line 7:
transient String passwordHash;— Tells the serialization engine to completely skip this field. During deserialization, transient fields are reset to their default value (nullfor objects,0for primitives), preventing sensitive credentials or security tokens from leaking into files or logs.