在Java中连接多个 .txt 文件

21

我有许多.txt文件,我想把它们连接起来生成一个文本文件。
我该如何在Java中实现?


以下是解答:

file1.txt file2.txt 

连接的结果为

file3.txt

使得 file1.txt内容file2.txt 的内容所跟随。


是的,我曾经在Unix命令中使用cat来完成这个任务。但是我现在想在我的程序中实现它。 - thetna
8
这是一个非常实际的问题,有几个人已经理解了并提供了有用的信息,比如指向FileUtils类的指针。 - Eric Wilson
是的,绝对是一个真正的问题。问了我想知道的内容,下面的答案很有帮助。 - csjacobs24
1
+1. 这是一个非常合理的问题,因为最短的纯Java答案需要11行代码。与UNIX shell中的#cat file1 file2 > file3进行比较。 - badbishop
5个回答

39

使用 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

此类中还有其他方法可以更优化地完成任务(例如使用列表)。

使用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);
    }
}

4
这个问题描述了使用通道(Channel)而不是将所有内容读入内存,可以显著提高性能。您还可以使用Guava的ByteSource.concat方法获取一个InputStream,其中包含所有被连接在一起的内容,然后将其传递给FileChannel.transferTo方法。 - Meredith

17

逐个读取文件并将它们写入目标文件。可以尝试如下代码:

    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();

我更喜欢这个,因为它可以扩展到超过两个文件,并且不需要在内存中保存太多内容。 - Brian Risk
@alexr,你能否再详细一些,逐步解释一下吗? - JoelBonetR
外层循环迭代文件。内层循环使用n字节长的缓冲区读取文件内容。有关详细信息,请查看Java流的任何教程。 - AlexR

4

对我来说这很好用。

// open file input stream to the first file file2.txt
InputStream in = new FileInputStream("file1.txt");
byte[] buffer = new byte[1 << 20];  // loads 1 MB of the file
// open file output stream to which files will be concatenated. 
OutputStream os = new FileOutputStream(new File("file3.txt"), true);
int count;
// read entire file1.txt and write it to file3.txt
while ((count = in.read(buffer)) != -1) {
    os.write(buffer, 0, count);
    os.flush();
}
in.close();
// open file input stream to the second file, file2.txt
in = new FileInputStream("file2.txt");
// read entire file2.txt and write it to file3.txt
while ((count = in.read(buffer)) != -1) {
    os.write(buffer, 0, count);
    os.flush();
}
in.close();
os.close();

你能逐步解释一下你的代码吗? - JoelBonetR
@JoelBonetR 我添加了一些注释来解释这段旧代码。不过,我认为上面的一些答案更好。 - Samer Makary

1

你的意思是需要一个文件包含其他文本文件的内容吗?那么,读取每个文件(可以在循环中完成),将它们的内容保存在StringBuffer/ArrayList中,并通过将这些保存的文本从StringBuffer/ArrayList刷新到最终的.txt文件来生成最终的.txt文件。

别担心,这是一项简单的任务。只要熟悉给定的系统,你就没问题了 :)


0

听起来像是作业...

  1. 打开文件1
  2. 打开文件2
  3. 创建/打开文件3
  4. 从文件1中读取并写入文件3
  5. 关闭文件1
  6. 从文件2中读取并写入文件3
  7. 关闭文件2
  8. 关闭文件3

如果你需要知道如何在Java中创建/打开/读取/写入/关闭文件,请搜索文档。那些信息应该是广泛可得的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接