温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java File文件如何读写

发布时间:2026-07-26 18:47:09 来源:亿速云 阅读:95 作者:小樊 栏目:编程语言

在 Java 中,File 本身只表示文件路径,真正进行读写需要配合 IO 流(Stream)或 NIO。下面按常见场景给你一个清晰、实用的说明。


一、File 与读写的关系

File file = new File("test.txt");

File 只表示文件或目录的抽象路径
❌ 不能直接读写内容

需要配合:

  • 字节流FileInputStream / FileOutputStream
  • 字符流FileReader / FileWriter
  • 缓冲流BufferedReader / BufferedWriter
  • NIO(推荐)Files

二、文本文件读写(最常用 ✅)

1️⃣ 写文本文件(FileWriter + BufferedWriter)

import java.io.*;

public class WriteFile {
    public static void main(String[] args) throws IOException {
        File file = new File("test.txt");

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.write("Hello Java");
            writer.newLine(); // 换行
            writer.write("文件写入成功");
        }
    }
}

✅ 自动关闭流(try-with-resources)


2️⃣ 读文本文件(BufferedReader)

import java.io.*;

public class ReadFile {
    public static void main(String[] args) throws IOException {
        File file = new File("test.txt");

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

三、字节文件读写(图片、视频等)

3️⃣ 拷贝文件(FileInputStream / FileOutputStream)

import java.io.*;

public class CopyFile {
    public static void main(String[] args) throws IOException {
        File src = new File("a.jpg");
        File dest = new File("b.jpg");

        try (InputStream in = new FileInputStream(src);
             OutputStream out = new FileOutputStream(dest)) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
        }
    }
}

四、Java 7+ 推荐方式:NIO Files(最简单 ✅)

4️⃣ 写文本

import java.nio.file.*;
import java.util.*;

public class NioWrite {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("test.txt");
        Files.write(path, Arrays.asList("第一行", "第二行"));
    }
}

5️⃣ 读文本

import java.nio.file.*;
import java.util.List;

public class NioRead {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("test.txt");
        List<String> lines = Files.readAllLines(path);
        lines.forEach(System.out::println);
    }
}

✅ 代码最少
✅ 自动处理编码(默认 UTF-8)


五、字符编码问题(很重要 ⚠️)

FileReader / FileWriter 默认使用系统编码,可能乱码。

✅ 推荐写法(指定 UTF-8):

new BufferedReader(
    new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)
);

六、如何选择?

场景 推荐方式
小文本文件 Files.readAllLines / write
大文本文件 BufferedReader / BufferedWriter
图片、视频 FileInputStream / FileOutputStream
新项目 ✅ NIO(Files)

七、常见错误

File file = new File("a.txt"); file.read()
✅ File 不能直接读写

❌ 忘记关闭流
✅ 使用 try-with-resources


如果你愿意,我也可以:

  • 给你 完整可运行示例
  • File 与 Path 的区别
  • 或针对 大文件 / 中文乱码 / 性能优化 深入讲解
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI