Skip to content

Java 文件与 IO ​

Java 使用路径定位文件,使用 IO 流读写数据。创建、读取和删除文件都可能失败,建议先了解 Java 异常 中的异常处理和资源关闭。

本文示例使用 Java 8 语法。代码片段需要放在方法中,相关类需要从 java.io、java.nio.file 等包导入。

File:表示文件或目录 ​

File 对象表示一个路径,创建对象时不会自动创建磁盘上的文件。

java
File file = new File("notes.txt"); // 相对路径,相对于程序当前工作目录。

System.out.println(file.exists());      // 文件或目录是否存在
System.out.println(file.isFile());      // 是否是普通文件
System.out.println(file.isDirectory()); // 是否是目录
System.out.println(file.getName());     // notes.txt
System.out.println(file.getAbsolutePath()); // 绝对路径

File 来自 java.io 包。相对路径的起点是程序的工作目录,不一定是源代码所在目录。

创建和删除 ​

java
File directory = new File("demo");
boolean createdDirectory = directory.mkdirs(); // 创建目录及不存在的父目录。

File file = new File(directory, "notes.txt");
boolean createdFile = file.createNewFile(); // 创建文件;已存在则返回 false。

boolean deleted = file.delete(); // 删除文件,成功返回 true。

createNewFile() 可能抛出 IOException,需要捕获或在方法上声明。mkdirs() 返回 false 不一定代表出错,也可能是目录已经存在;delete() 返回 false 表示未能删除。删除目录时,目录必须为空。

上例中的 delete() 会真正删除文件,实际使用时要确认路径。

遍历目录 ​

java
File directory = new File("demo");
File[] entries = directory.listFiles();

if (entries != null) { // 路径不是目录或发生 IO 错误时可能返回 null。
    for (File entry : entries) {
        System.out.println(entry.getName());
    }
}

listFiles() 只列出当前目录下的直接子项,不会自动遍历子目录。

Path 和 Files:处理路径与文件 ​

Path 表示路径;Files 提供创建、复制、移动和读写等静态方法。相比通过 File 的布尔返回值判断失败,Files 方法通常会抛出异常,便于了解失败原因。

java
Path path = Paths.get("demo", "notes.txt"); // Java 8 写法。
System.out.println(path.getFileName());       // notes.txt
System.out.println(Files.exists(path));

Files.createDirectories(path.getParent()); // 父目录已存在时也可以正常执行。
if (!Files.exists(path)) {
    Files.createFile(path);
}

示例中的文件操作可能抛出 IOException。Files.exists() 只能反映检查时的状态;如果其他程序同时修改文件,检查和创建之间的状态可能变化,创建操作仍需处理异常。

字节流与字符流 ​

字节流与字符流

类型适合处理常见类
字节流图片、音频等二进制数据,也可处理文本字节InputStream、OutputStream
字符流按字符读写文本Reader、Writer

读写文本时要明确字符编码,例如 UTF-8;读写使用的编码不一致可能导致乱码。

文件字节流 ​

FileInputStream 从文件读取字节,FileOutputStream 向文件写入字节,适合处理图片、音频等二进制文件。它们分别是 InputStream 和 OutputStream 的子类。

java
// 将图片复制到另一个文件;目标文件存在时会被覆盖。
try (FileInputStream input = new FileInputStream("photo.jpg");
     FileOutputStream output = new FileOutputStream("photo-copy.jpg")) {
    byte[] buffer = new byte[8192];
    int count;
    while ((count = input.read(buffer)) != -1) {
        output.write(buffer, 0, count);
    }
} catch (IOException e) {
    System.out.println("复制失败:" + e.getMessage());
}

read(buffer) 返回实际读取的字节数,到文件末尾时返回 -1;写入时只写入本次读取的有效字节。FileOutputStream 默认覆盖已有文件,使用 new FileOutputStream("data.bin", true) 可以追加。

文件字符流 ​

FileReader 从文件读取字符,FileWriter 向文件写入字符,分别是 Reader 和 Writer 的子类,适合处理纯文本。

java
// 逐块读取并复制文本;目标文件存在时会被覆盖。
try (FileReader reader = new FileReader("notes.txt");
     FileWriter writer = new FileWriter("notes-copy.txt")) {
    char[] buffer = new char[1024];
    int count;
    while ((count = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, count);
    }
} catch (IOException e) {
    System.out.println("复制失败:" + e.getMessage());
}

read(buffer) 返回实际读取的字符数,到文件末尾时返回 -1。FileWriter 默认覆盖已有文件,使用 new FileWriter("notes.txt", true) 可以追加。Java 8 中这两个类使用系统默认字符编码;需要明确指定编码时,可以使用下面的 Files.newBufferedReader() 和 Files.newBufferedWriter()。

读取文本 ​

java

public class ReadTextDemo {
    public static void main(String[] args) {
        Path path = Paths.get("notes.txt");

        // try 结束时自动关闭 reader。
        try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("读取失败:" + e.getMessage());
        }
    }
}

readLine() 每次读取一行,不包含换行符;读到文件末尾时返回 null。

写入文本 ​

java

public class WriteTextDemo {
    public static void main(String[] args) {
        Path path = Paths.get("notes.txt");

        // 文件不存在则创建;存在则在末尾追加。
        try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
            writer.write("今天学习 Java IO");
            writer.newLine();
        } catch (IOException e) {
            System.out.println("写入失败:" + e.getMessage());
        }
    }
}

不传打开选项时,Files.newBufferedWriter() 默认会创建文件;如果文件已存在,会清空原有内容再写入。需要保留旧内容时,应明确使用 APPEND。

复制文件 ​

java
Path source = Paths.get("photo.jpg");
Path target = Paths.get("photo-copy.jpg");

Files.copy(source, target); // 目标已存在时默认抛出异常。

Files.copy 适合直接复制文件。需要覆盖已有目标时,可以传入 StandardCopyOption.REPLACE_EXISTING;使用前应确认目标文件可以被覆盖。

使用时注意 ​

  • File 和 Path 描述路径,本身不会读取文件内容。
  • 文件读写可能抛出 IOException,要处理文件不存在、权限不足等情况。
  • 通过 try-with-resources 管理实现了 AutoCloseable 的资源,避免忘记关闭。
  • 操作前确认路径和打开方式,尤其是删除、覆盖文件时。

Properties ​

Properties 常用于保存字符串键值对:setProperty() 设置属性,getProperty() 获取属性,stringPropertyNames() 获取属性名集合。

java
public class PropertiesDemo1 {
    public static void main(String[] args) {
        Properties prop = new Properties();

        prop.setProperty("username", "admin");
        prop.setProperty("password", "123456");

        String username = prop.getProperty("username");
        String password = prop.getProperty("password");

        System.out.println(username);
        System.out.println(password);

        System.out.println("--------------------------");

        Set<String> keySet = prop.stringPropertyNames();

        for (String key : keySet) {
            System.out.println(key + "---" + prop.getProperty(key));
        }
    }
}

load() 从字节流或字符流读取属性,store() 将属性写入字节流或字符流,第二个参数用于添加注释。

java
public class PropertiesDemo2 {
    public static void main(String[] args) throws IOException {
        Properties prop = new Properties();
        prop.setProperty("name", "zhangsan");
        prop.setProperty("age", "23");

        FileWriter fos = new FileWriter("day04\\test.properties");

        prop.store(fos,null);

        fos.close();
    }

    private static void method() throws IOException {
        Properties prop = new Properties();

        FileInputStream fis = new FileInputStream("day04\\config.properties");

        prop.load(fis);

        fis.close();

        System.out.println(prop);
    }
}
最近更新