Java File Processing

"File processing allows your programs to persist data beyond a single run — reading saved information on startup and writing updated information when done."- Claude 2026

File Processing

So far our programs have stored data in variables and collections that disappear when the program ends. File processing lets you read data from a file and write data back to a file, so information can persist between runs.

Java handles file I/O through classes in the java.io package. The most common approach for text files uses:

All file operations can throw exceptions — errors that occur at runtime, such as a file not being found or a disk being full. Java requires you to handle these using a try/catch block, or declare them with throws in the method signature.

Working with Your File

Before writing any code, it helps to think about the file itself:

For our examples we'll use a file called party.txt that stores one character per line in the format name,class:

Hero,Warrior
Zara,Mage
Fletch,Archer
TIP: If you use a comma as a separator, avoid commas in your data values. A consistent, simple format makes reading the file much easier.
Processing in Java

Java file I/O follows a consistent pattern regardless of whether you are reading or writing:

  1. Open the file by creating a reader or writer object
  2. Process the file — read lines or write lines in a loop
  3. Close the file when done to release system resources

The try-with-resources syntax handles closing automatically — the file is closed as soon as the try block exits, even if an exception occurs. This is the recommended approach.

Writing to a File
import java.io.*;

public class FileWrite {

    public static void main(String[] args) {

        // try-with-resources: file closes automatically when done
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("party.txt"))) {

            writer.write("Hero,Warrior");
            writer.newLine();
            writer.write("Zara,Mage");
            writer.newLine();
            writer.write("Fletch,Archer");
            writer.newLine();

            System.out.println("File written successfully.");

        } catch (IOException e) {
            System.out.println("Error writing file: " + e.getMessage());
        }

    }

}
File written successfully.
TIP: By default, FileWriter overwrites the file if it already exists. To append to an existing file instead of overwriting it, pass true as a second argument: new FileWriter("party.txt", true)
Reading from a File
import java.io.*;

public class FileRead {

    public static void main(String[] args) {

        try (BufferedReader reader = new BufferedReader(new FileReader("party.txt"))) {

            String line;

            // readLine() returns null when the end of the file is reached
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }

    }

}
Hero,Warrior
Zara,Mage
Fletch,Archer
Parsing Each Line

When each line contains multiple values separated by a delimiter, use split() to break the line into parts. The result is an array of strings.

import java.io.*;

public class FileParse {

    public static void main(String[] args) {

        try (BufferedReader reader = new BufferedReader(new FileReader("party.txt"))) {

            String line;

            while ((line = reader.readLine()) != null) {
                // Split on comma to get name and class
                String[] parts = line.split(",");
                String name      = parts[0];
                String charClass = parts[1];
                System.out.println(name + " is a " + charClass);
            }

        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }

    }

}
Hero is a Warrior
Zara is a Mage
Fletch is a Archer
Complete Read/Write Application
This complete example combines reading and writing in one program. It reads an existing party file into an ArrayList of Character objects, adds a new character, then writes the entire updated list back to the file.
import java.io.*;
import java.util.ArrayList;

public class PartyFile {

    // Simple Character class
    static class Character {
        String name;
        String charClass;

        Character(String name, String charClass) {
            this.name = name;
            this.charClass = charClass;
        }

        @Override
        public String toString() {
            return name + " (" + charClass + ")";
        }
    }

    // Read party.txt and return a list of Character objects
    static ArrayList<Character> readParty(String filename) {
        ArrayList<Character> party = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 2) {
                    party.add(new Character(parts[0].trim(), parts[1].trim()));
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("No existing file found. Starting with empty party.");
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }

        return party;
    }

    // Write the party list back to file
    static void writeParty(String filename, ArrayList<Character> party) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
            for (Character c : party) {
                writer.write(c.name + "," + c.charClass);
                writer.newLine();
            }
            System.out.println("Party saved to " + filename);
        } catch (IOException e) {
            System.out.println("Error writing file: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        String filename = "party.txt";

        // Read existing party from file
        ArrayList<Character> party = readParty(filename);

        System.out.println("Loaded party:");
        for (Character c : party) {
            System.out.println("  " + c);
        }

        // Add a new character
        party.add(new Character("Dray", "Rogue"));
        System.out.println("\nAdded: Dray (Rogue)");

        // Write updated party back to file
        writeParty(filename, party);

        // Read it back to confirm
        System.out.println("\nUpdated party from file:");
        for (Character c : readParty(filename)) {
            System.out.println("  " + c);
        }
    }

}
Running this program (assuming party.txt already contains Hero, Zara, and Fletch) outputs:
Loaded party:
  Hero (Warrior)
  Zara (Mage)
  Fletch (Archer)

Added: Dray (Rogue)
Party saved to party.txt

Updated party from file:
  Hero (Warrior)
  Zara (Mage)
  Fletch (Archer)
  Dray (Rogue)
Running the Application

Save the file as PartyFile.java in the same folder as party.txt, then compile and run from the terminal:

  1. Download and install the Java Development Kit (JDK) if you haven't already.
  2. Create party.txt in the same folder with a few characters in name,class format, one per line.
  3. Compile: javac PartyFile.java
  4. Run: java PartyFile
→ This page was created with help from Gemini and Claude AI.