File IO

File operations are an important program feature. This lesson covers file IO in Java.

File Class

The File class is used to operate on files and directories.

Creating File Objects

JAVA
import java.io.File;

// Method 1: Path string
File file1 = new File("test.txt");

// Method 2: Parent path + filename
File file2 = new File("/home/user", "test.txt");

// Method 3: File object + filename
File dir = new File("/home/user");
File file3 = new File(dir, "test.txt");

Common Methods

Method Description
exists() Exists
isFile() Is file
isDirectory() Is directory
getName() Get filename
getPath() Get path
getAbsolutePath() Get absolute path
length() File size (bytes)
createNewFile() Create file
mkdir() Create directory
mkdirs() Create nested directories
delete() Delete
list() List directory contents

Example: File Operations

JAVA
import java.io.File;
import java.io.IOException;

public class FileDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("test.txt");
        
        // Create file
        if (!file.exists()) {
            file.createNewFile();
            System.out.println("File created successfully");
        }
        
        // File info
        System.out.println("Filename: " + file.getName());
        System.out.println("Path: " + file.getPath());
        System.out.println("Absolute path: " + file.getAbsolutePath());
        System.out.println("Size: " + file.length() + " bytes");
        System.out.println("Is file: " + file.isFile());
        System.out.println("Is directory: " + file.isDirectory());
        
        // Delete file
        // file.delete();
    }
}
▶ Try it Yourself

Example: Directory Operations

JAVA
import java.io.File;

public class DirectoryDemo {
    public static void main(String[] args) {
        // Create directory
        File dir = new File("testdir/subdir");
        dir.mkdirs();
        System.out.println("Directory created: " + dir.getAbsolutePath());
        
        // List directory contents
        File parent = new File("testdir");
        String[] files = parent.list();
        if (files != null) {
            for (String name : files) {
                System.out.println("  " + name);
            }
        }
        
        // Traverse directory
        File[] fileArray = parent.listFiles();
        if (fileArray != null) {
            for (File f : fileArray) {
                String type = f.isDirectory() ? "[DIR]" : "[FILE]";
                System.out.println(type + " " + f.getName());
            }
        }
    }
}
▶ Try it Yourself

File Read/Write

BufferedReader Read File

JAVA
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
    public static void main(String[] args) {
        // try-with-resources auto-closes resources
        try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("Read failed: " + e.getMessage());
        }
    }
}

BufferedWriter Write File

JAVA
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFile {
    public static void main(String[] args) {
        // Overwrite
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
            writer.write("Hello, World!");
            writer.newLine();
            writer.write("Java file operations");
            System.out.println("Write successful");
        } catch (IOException e) {
            System.out.println("Write failed: " + e.getMessage());
        }
        
        // Append
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt", true))) {
            writer.write("Appended content");
            writer.newLine();
            System.out.println("Append successful");
        } catch (IOException e) {
            System.out.println("Append failed: " + e.getMessage());
        }
    }
}

try-with-resources

Introduced in Java 7, automatically closes resources that implement AutoCloseable.

Syntax

JAVA
try (ResourceType variable = new Resource()) {
    // Use resource
} catch (ExceptionType e) {
    // Handle exception
}

Example: File Copy

JAVA
import java.io.*;

public class FileCopy {
    public static void copy(String src, String dest) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(src));
             BufferedWriter writer = new BufferedWriter(new FileWriter(dest))) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }
        }
        System.out.println("Copy complete");
    }
    
    public static void main(String[] args) {
        try {
            copy("source.txt", "dest.txt");
        } catch (IOException e) {
            System.out.println("Copy failed: " + e.getMessage());
        }
    }
}
▶ Try it Yourself

Read All Content

Method 1: Line by Line

JAVA
public static String readAll(String filename) throws IOException {
    StringBuilder sb = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
    }
    return sb.toString();
}

Method 2: Files Utility Class (Java 7+)

JAVA
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;

public class FilesDemo {
    public static void main(String[] args) throws IOException {
        // Read all lines
        List<String> lines = Files.readAllLines(Paths.get("test.txt"));
        lines.forEach(System.out::println);
        
        // Read as string
        String content = new String(Files.readAllBytes(Paths.get("test.txt")));
        System.out.println(content);
        
        // Write file
        Files.write(Paths.get("output.txt"), "Hello".getBytes());
    }
}

File Traversal

Recursive Directory Listing

JAVA
import java.io.File;

public class ListFiles {
    public static void listFiles(File dir, String indent) {
        File[] files = dir.listFiles();
        if (files == null) return;
        
        for (File file : files) {
            System.out.println(indent + file.getName());
            if (file.isDirectory()) {
                listFiles(file, indent + "  ");
            }
        }
    }
    
    public static void main(String[] args) {
        File dir = new File(".");
        listFiles(dir, "");
    }
}

File Filtering

JAVA
import java.io.File;
import java.io.FilenameFilter;

public class FileFilter {
    public static void main(String[] args) {
        File dir = new File(".");
        
        // List only .txt files
        String[] txtFiles = dir.list((d, name) -> name.endsWith(".txt"));
        if (txtFiles != null) {
            for (String name : txtFiles) {
                System.out.println(name);
            }
        }
        
        // List only directories
        File[] dirs = dir.listFiles(File::isDirectory);
        if (dirs != null) {
            for (File d : dirs) {
                System.out.println("[DIR] " + d.getName());
            }
        }
    }
}

Serialization

Convert objects to byte streams for saving to files or network transmission.

Serialization Requirements

Example: Serialization

JAVA
import java.io.*;

// Serializable class
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    private transient String password;  // transient excludes from serialization
    
    public User(String name, int age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
    }
    
    @Override
    public String toString() {
        return "User{name='" + name + "', age=" + age + ", password='" + password + "'}";
    }
}

public class SerializeDemo {
    public static void main(String[] args) {
        // Serialize
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.dat"))) {
            User user = new User("Alice", 25, "123456");
            oos.writeObject(user);
            System.out.println("Serialization successful");
        } catch (IOException e) {
            System.out.println("Serialization failed: " + e.getMessage());
        }
        
        // Deserialize
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.dat"))) {
            User user = (User) ois.readObject();
            System.out.println("Deserialized: " + user);
            // User{name='Alice', age=25, password='null'} (password excluded)
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("Deserialization failed: " + e.getMessage());
        }
    }
}
▶ Try it Yourself

❓ Frequently Asked Questions

Q What's the difference between relative and absolute paths?
A Relative paths are relative to the current working directory. Absolute paths start from the root directory.
Q Why use try-with-resources?
A Automatically closes resources, preventing resource leaks. More concise than manual finally.
Q What does the transient keyword do?
A Marks fields that should not participate in serialization.

📖 Summary

📝 Exercises

  1. File statistics: Count lines, words, and characters in a file
  2. File copy: Implement file copy with support for large files
  3. Directory traversal: Recursively list all files in a directory, sorted by size

Next Lesson

In the next lesson, we'll learn about Streams and NIO — Java's stream-based IO.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏