上一篇                     
               
			  Java怎么读写文件?
- 后端开发
- 2025-05-30
- 2134
 在Java中操作文件主要通过
 
 
java.io.File类实现,支持创建、删除、重命名及检查文件属性等基础功能,结合
 FileInputStream/
 FileOutputStream可读写字节数据,使用
 FileReader/
 FileWriter处理字符流,NIO包的
 Files和
 Paths类提供更高效的文件操作,如复制、移动及遍历目录。
在Java中处理文件操作是开发中的常见需求,涉及文件读写、上传、下载等多种场景,下面通过实际代码示例和最佳实践详细讲解核心操作方法:
文件读写基础(java.io包)
文本文件读写
import java.io.*;
public class TextFileExample {
    // 写入文本文件
    public static void writeFile(String path, String content) throws IOException {
        try (FileWriter writer = new FileWriter(path)) {
            writer.write(content);
            System.out.println("文件写入成功");
        }
    }
    // 读取文本文件
    public static String readFile(String path) throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("n");
            }
        }
        return content.toString();
    }
    public static void main(String[] args) {
        String filePath = "demo.txt";
        try {
            writeFile(filePath, "你好,这是测试内容n第二行文本");
            System.out.println("文件内容:n" + readFile(filePath));
        } catch (IOException e) {
            System.err.println("文件操作错误: " + e.getMessage());
        }
    }
} 
二进制文件操作(如图片/视频)
import java.nio.file.*;
public class BinaryFileExample {
    // 保存字节数据到文件
    public static void saveBinaryFile(byte[] data, String path) throws IOException {
        Files.write(Paths.get(path), data);
    }
    // 读取文件为字节数组
    public static byte[] readBinaryFile(String path) throws IOException {
        return Files.readAllBytes(Paths.get(path));
    }
} 
高效文件处理(NIO包)
Java NIO提供更高效的文件操作API:
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class NioExample {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("nio_demo.txt");
        // 写入文件(覆盖模式)
        Files.write(path, 
                   "NIO写入示例".getBytes(StandardCharsets.UTF_8),
                   StandardOpenOption.CREATE,
                   StandardOpenOption.TRUNCATE_EXISTING);
        // 追加内容
        Files.write(path, 
                   "n追加内容".getBytes(),
                   StandardOpenOption.APPEND);
        // 读取所有行
        List<String> lines = Files.readAllLines(path);
        lines.forEach(System.out::println);
    }
} 
Web文件上传(Servlet示例)
前端HTML表单
<form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <button type="submit">上传</button> </form>
Servlet处理上传
@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        Part filePart = request.getPart("file");
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
        // 保存到服务器指定目录
        try (InputStream fileContent = filePart.getInputStream()) {
            Files.copy(fileContent, 
                      Paths.get("/uploads/" + fileName),
                      StandardCopyOption.REPLACE_EXISTING);
        }
        response.getWriter().print("上传成功: " + fileName);
    }
} 
关键注意事项
-  异常处理 – 必须捕获IO异常: try { Files.readAllBytes(Paths.get("file.txt")); } catch (IOException e) { System.err.println("错误: " + e.getClass().getSimpleName() + " - " + e.getMessage()); }
-  资源关闭 – 使用try-with-resources自动关闭:  try (FileInputStream fis = new FileInputStream("data.bin")) { // 自动关闭资源 }
-  文件安全: - 验证上传文件类型:String contentType = Files.probeContentType(path)
- 限制上传文件大小(@MultipartConfig注解配置)
 
- 验证上传文件类型:
-  路径处理建议: - 使用相对路径:Paths.get("data/files/")
- 跨平台路径分隔符:File.separator
 
- 使用相对路径:
高级场景处理
大文件分块读取
try (BufferedReader br = Files.newBufferedReader(Paths.get("large.log"))) {
    String line;
    while ((line = br.readLine()) != null) {
        // 逐行处理大文件
    }
} 
文件监控(WatchService)
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get("/monitor");
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
    WatchKey key = watchService.take();
    for (WatchEvent<?> event : key.pollEvents()) {
        if (event.kind() == ENTRY_MODIFY) {
            System.out.println("文件修改: " + event.context());
        }
    }
    key.reset();
} 
-  选择正确API:  - 小文件:Files.readAllBytes()/Files.write()
- 大文件:缓冲流(BufferedInputStream)或NIO Channel
 
- 小文件:
-  字符编码 – 始终明确指定: new String(Files.readAllBytes(path), StandardCharsets.UTF_8); 
-  临时文件处理: Path tempFile = Files.createTempFile("prefix_", ".tmp"); tempFile.toFile().deleteOnExit(); // 程序退出时删除
-  新版JDK特性(JDK11+):  Files.writeString(Path.of("new.txt"), "内容"); // 直接写入字符串 String content = Files.readString(Path.of("file.txt"));
引用说明:本文代码基于Java 17 API规范编写,文件操作遵循Oracle官方文档推荐实践,Servlet示例需Tomcat 10+支持,NIO特性要求JDK 7及以上版本,安全建议参考OWASP文件上传防护指南。
 
  
			 
			 
			 
			 
			 
			 
			 
			