Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Object Serialization and Print Streams

Tech May 18 2

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:

  1. The serial version UID of the class doesn't match the one stored in the stream
  2. The class contains unknown data types
  3. 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 when println(), printf(), or format() is called
  • false: 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);
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.