Java Object Serialization and Print Streams
Object Serialization and Deserialization
Writing objects to a stream using ObjectOutputStream is called serialization. Reading objects from a stream using ObjectInputStream is called deserialization.
Creating a Serializable Class
To serialize an object, the class must implement the Serializable interface:
public class User implements Serializable {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
The Serializable interface has no methods to implement—it serves as a marker that indicates the class can be serialized.
InvalidClassException
When deserializing an object, if the class definition has been modified after serialization, an InvalidClassException may occur. This happens when:
- The serial version UID of the class doesn't match the one stored in the stream
- The class contains unknown data types
- The class lacks an accessible no-argument constructor
If a field is changed from private to public after serialization, deserialization will throw an InvalidClassException because the serial version changes automatically.
To exclude fields from serialization, use the static or transient modifiers:
public class User implements Serializable {
private String name;
private static int version; // not serialized
private transient int cacheId; // not serialized
}
Print Streams
Java provides two types of print streams:
- PrintStream: byte-based output stream
- PrintWriter: character-based output stream
Example using PrintWriter:
FileWriter fw = new FileWriter("output.txt");
PrintWriter writer = new PrintWriter(fw, true); // true enables auto-flush
writer.println("Data line 1");
writer.println("Data line 2");
writer.flush();
writer.close();
The second constructor parameter controls auto-flush behavior:
true: auto-flushes whenprintln(),printf(), orformat()is calledfalse: manual flushing required
Apache Commons-IO Utility
The Commons-IO library provides convenient file manipulation methods. Ensure the JAR file is added to your project's classpath before use.
Common Methods
| Method | Purpose |
|---|---|
getExtension(String path) |
Extracts file extension |
getName(String filename) |
Gets filename from path |
isExtension(String file, String ext) |
Checks if file has specific extension |
readFileToString(File file) |
Reads entire fille into String |
writeStringToFile(File file, String content) |
Writes String to file |
copyDirectoryToDirectory(File src, File dest) |
Copies entire directory |
copyFile(File src, File dest) |
Copies single file |
Usage Example
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.IOException;
public class CommonsIOExample {
public static void main(String[] args) throws IOException {
// Get file extension
String extension = FilenameUtils.getExtension("C:\\data\\report.pdf");
System.out.println("Extension: " + extension);
// Get filename only
String filename = FilenameUtils.getName("C:\\data\\report.pdf");
System.out.println("Filename: " + filename);
// Check extension
boolean isJava = FilenameUtils.isExtension("C:\\data\\Main.java", "java");
System.out.println("Is Java: " + isJava);
// Copy directory
FileUtils.copyDirectoryToDirectory(
new File("C:\\source_folder"),
new File("C:\\target_folder")
);
// Copy file
FileUtils.copyFile(
new File("C:\\data\\input.txt"),
new File("C:\\backup\\input.txt")
);
// Write content to file
FileUtils.writeStringToFile(
new File("C:\\data\\log.txt"),
"Application started successfully"
);
// Read file content
String content = FileUtils.readFileToString(new File("C:\\data\\config.txt"));
System.out.println("File content: " + content);
}
}