CodeGym /Courses /JAVA 25 SELF /Handling Corrupted Files, Data Recovery

Handling Corrupted Files, Data Recovery

JAVA 25 SELF
Level 38, Lesson 2
Available

1. Signs of Corrupted Files

In a perfect world, files are always read and written without errors, and the data inside them is like freshly baked rolls—soft, fragrant, neat, intact. But in reality, files can be “broken,” “crooked,” “partial,” or “the wrong format.” The reasons may vary. For example, a write failure to disk (due to a sudden power outage), network errors during file transfer, or media failure (the good old bad sector). Manual editing of a file in an inappropriate program can also damage it, as can a mismatch between the expected and actual data format.

In Java, such situations usually manifest as exceptions during read/write operations, and sometimes—as strange program behavior (for example, the data suddenly ends or you see gibberish).

Exceptions when reading

The clearest sign is unexpected exceptions. Here are some of them:

  • EOFException — unexpected end of file (End Of File). You expected more data in the file, but there isn’t any.
  • MalformedInputException (or, in older APIs, MalformedInputException from NIO) — the file does not match the expected encoding or structure.
  • ZipException — if you try to read an archive as a regular file.
  • StreamCorruptedException — when reading serialized objects if the file is corrupted.

Data format mismatch

Sometimes the file is read without an exception, but its contents do not match the expected format:

  • You expected a string but got a set of incomprehensible characters.
  • You expected a certain number of numbers, but there are fewer.
  • You expected a CSV file, but it’s JSON (or vice versa).

Real-world example

Suppose you’re writing an application that stores a to-do list in a text file. The program expects each line to be a separate task. But the user decided to open the file in Excel, made changes, saved it in a different format... and now your program can’t read the file.

2. Strategies for Handling Corrupted Files

Logging and informing the user

First rule: don’t panic! (and don’t let the user panic). Always log the error and inform the user if something goes wrong. But you don’t have to describe all the horrors of a Java stack trace.

try {
    // reading the file
} catch (EOFException e) {
    System.err.println("The file ended unexpectedly. It may be corrupted.");
    // log details
    e.printStackTrace();
}

Attempting partial recovery

Sometimes you can “save” at least part of the data. For example, if the file is read line by line, you can process all lines up to the first error.

Using backups (backup)

Serious applications often create backups of important files before writing. If the main file is corrupted, you can try to restore the data from the backup.

3. Practice: Reading a File with an Unexpected End (EOF)

Classic scenario

Suppose we have a binary file where int values are written sequentially. The program expects exactly 5, but the file was corrupted and only 3 were written.

import java.io.*;

public class DamagedFileExample {
    public static void main(String[] args) {
        String filename = "numbers.bin";

        // For example: create a file with 3 numbers (instead of 5)
        try (DataOutputStream out = new DataOutputStream(new FileOutputStream(filename))) {
            out.writeInt(42);
            out.writeInt(7);
            out.writeInt(2024);
            // out.writeInt(1); out.writeInt(2); // intentionally do not write!
        } catch (IOException e) {
            System.err.println("Error creating the file: " + e.getMessage());
        }

        // Now try to read 5 numbers
        try (DataInputStream in = new DataInputStream(new FileInputStream(filename))) {
            for (int i = 0; i < 5; i++) {
                int number = in.readInt();
                System.out.println("Read number: " + number);
            }
        } catch (EOFException e) {
            System.err.println("The file ended unexpectedly! It may be corrupted.");
        } catch (IOException e) {
            System.err.println("Read error: " + e.getMessage());
        }
    }
}

Output:

Read number: 42
Read number: 7
Read number: 2024
The file ended unexpectedly! It may be corrupted.

Reading until the first error

It is often reasonable to read data in a loop until an exception occurs. This way you can retrieve at least some information.

try (DataInputStream in = new DataInputStream(new FileInputStream(filename))) {
    while (true) {
        try {
            int number = in.readInt();
            System.out.println("Read number: " + number);
        } catch (EOFException e) {
            System.out.println("No more data (or the file is corrupted).");
            break;
        }
    }
} catch (IOException e) {
    System.err.println("Read error: " + e.getMessage());
}

4. Working with Text Files and Encodings

Encoding issue

If a file was written in one encoding and read in another, decoding errors are possible:

import java.nio.charset.*;

try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(new FileInputStream("tasks.txt"), "UTF-8"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (MalformedInputException e) {
    System.err.println("Encoding error! The file is corrupted or not written in UTF-8.");
} catch (IOException e) {
    System.err.println("Read error: " + e.getMessage());
}

Important: Sometimes, instead of an exception, you’ll get garbled text — that’s also a sign of corruption or the wrong encoding.

How to handle it?

  • Inform the user about the issue.
  • Try opening the file with a different encoding.
  • If the data is critical, suggest restoring from a backup.

5. Data Recovery: Strategies

Reading partially valid data

If the file structure allows it, you can extract at least the data that was successfully read before the error. For example, if the file is a list of lines (one task per line), you can process all lines up to the failure.

try (BufferedReader reader = new BufferedReader(new FileReader("tasks.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        // process the line
    }
} catch (IOException e) {
    System.err.println("Read error: " + e.getMessage());
    // You can save the data already read or prompt the user to recover
}

Using backup files

If you create a copy of the file in advance (for example, tasks.txt.bak), you can restore data from it:

File original = new File("tasks.txt");
File backup = new File("tasks.txt.bak");

if (!original.exists() && backup.exists()) {
    // Copy the backup to the original location
    Files.copy(backup.toPath(), original.toPath(), StandardCopyOption.REPLACE_EXISTING);
    System.out.println("Restore from backup completed.");
}

Checksums and validation

For important files, you can store a checksum (e.g., MD5 or SHA-256) and compare it with the current one each time the file is opened. If they don’t match, the file is corrupted.

// Rough outline (hashing implementation omitted for brevity)
String expectedHash = "..."; // previously saved hash
String actualHash = calculateFileHash("tasks.txt");
if (!expectedHash.equals(actualHash)) {
    System.out.println("The file tasks.txt is corrupted! Try restoring it from a backup.");
}

6. Common Mistakes When Handling Corrupted Files

Error No. 1: The file format is not validated. If you expect each line to be, for example, a number but it’s text, you’ll get a NumberFormatException. It’s better to validate data as you read.

Error No. 2: Missing try-with-resources. If you don’t use try-with-resources, the file may remain “hanging” (not closed) even on error, which will make recovery or deletion harder.

Error No. 3: Overwriting a corrupted file without creating a backup. If you immediately overwrite the file on error, the chance of recovery decreases. It’s better to save a backup first.

Error No. 4: Uninformative recovery. The user should know that the file was corrupted and restored from a backup — otherwise they may not understand why part of the data disappeared.

1
Task
JAVA 25 SELF, level 38, lesson 2
Locked
Decoding an Ancient Message: awaiting the full text 🧩
Decoding an Ancient Message: awaiting the full text 🧩
1
Task
JAVA 25 SELF, level 38, lesson 2
Locked
Security Audit: Secret Dossier Authenticity Check 🛡️
Security Audit: Secret Dossier Authenticity Check 🛡️
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION