You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Java NIO Files合并两个文件内容至新文件时仅保留第二个文件内容的问题求助

Java NIO Files合并两个文件内容至新文件时仅保留第二个文件内容的问题求助

嘿,我来帮你排查这个问题~

你遇到的情况其实是Files.write()方法的默认行为导致的:当你第一次调用它写入txt1的内容时,新文件会被创建并写入内容;但第二次调用它写入txt2的内容时,默认是覆盖掉文件里已有的内容,而不是追加进去,所以最后新文件里就只剩txt2的内容啦。

给你两种简单的解决办法:

方法一:合并内容后一次性写入

把两个文件的内容都读到同一个列表里,然后一次性写入新文件,这样就不会有覆盖的问题:

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

public class Example2 {
    public static void main(String[] args) throws IOException {
        Path oldFile1 = Paths.get("D:\\sample\\txt1.txt");
        Path oldFile2 = Paths.get("D:\\sample\\txt2.txt");
        Path newFile = Paths.get("D:\\sample\\newFile.txt");

        // 合并两个文件的内容到同一个集合
        List<String> allLines = new ArrayList<>();
        allLines.addAll(Files.readAllLines(oldFile1));
        allLines.addAll(Files.readAllLines(oldFile2));

        // 一次性写入新文件
        Files.write(newFile, allLines);
    }
}

方法二:使用追加模式写入

在第二次写入的时候,指定StandardOpenOption.APPEND参数,让文件以追加的方式写入内容,而不是覆盖:

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

public class Example2 {
    public static void main(String[] args) throws IOException {
        Path oldFile1 = Paths.get("D:\\sample\\txt1.txt");
        Path oldFile2 = Paths.get("D:\\sample\\txt2.txt");
        Path newFile = Paths.get("D:\\sample\\newFile.txt");

        // 第一次写入:创建文件并写入第一个文件内容
        Files.write(newFile, Files.readAllLines(oldFile1));
        // 第二次写入:以追加模式写入第二个文件内容
        Files.write(newFile, Files.readAllLines(oldFile2), StandardOpenOption.APPEND);
    }
}

小提醒:如果你的文件特别大,用readAllLines会把整个文件内容加载到内存里,可能会有内存压力,这时候可以考虑用流式的方式逐行读取写入,但对于普通大小的文件,上面两种方法完全够用啦~

备注:内容来源于stack exchange,提问作者chandana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 15:15:28