在java中连接多个.txt文件

the*_*tna 16 java concatenation

我有很多.txt文件.我想连接这些并生成一个文本文件.我怎么在java中做到这一点?以下是这种情况

        file1.txt file2.txt 
Run Code Online (Sandbox Code Playgroud)

连接结果

             file3.txt
Run Code Online (Sandbox Code Playgroud)

这样file1.txt就遵循 了内容file2.txt

Pau*_*gas 34

使用 Apache Commons IO

您可以使用Apache Commons IO库.这是FileUtils班级.

// Files to read
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");

// File to write
File file3 = new File("file3.txt");

// Read the file as string
String file1Str = FileUtils.readFileToString(file1);
String file2Str = FileUtils.readFileToString(file2);

// Write the file
FileUtils.write(file3, file1Str);
FileUtils.write(file3, file2Str, true); // true for append
Run Code Online (Sandbox Code Playgroud)

此类中还有其他方法可以帮助以更优化的方式完成任务(例如,使用列表).

使用 Java 7+

如果您使用的是Java 7+

public static void main(String[] args) throws Exception {
    // Input files
    List<Path> inputs = Arrays.asList(
            Paths.get("file1.txt"),
            Paths.get("file2.txt")
    );

    // Output file
    Path output = Paths.get("file3.txt");

    // Charset for read and write
    Charset charset = StandardCharsets.UTF_8;

    // Join files (lines)
    for (Path path : inputs) {
        List<String> lines = Files.readAllLines(path, charset);
        Files.write(output, lines, charset, StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • [这个问题](http://stackoverflow.com/questions/1605332/java-nio-filechannel-versus-fileoutputstream-performance-usefulness)描述了使用频道而不是将所有内容都读入内存的明显更好的性能.您还可以使用Guava的ByteSource.concat来获取连接的所有内容的InputStream,然后将其传递给FileChannel.transferTo (3认同)

Ale*_*exR 15

逐个文件读取并将它们写入目标文件.类似于以下内容:

    OutputStream out = new FileOutputStream(outFile);
    byte[] buf = new byte[n];
    for (String file : files) {
        InputStream in = new FileInputStream(file);
        int b = 0;
        while ( (b = in.read(buf)) >= 0)
            out.write(buf, 0, b);
        in.close();
    }
    out.close();
Run Code Online (Sandbox Code Playgroud)