是否可以使用java在不阅读行的情况下合并两个文本文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18655402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:53:57  来源:igfitidea点击:

Is it possible to merge two text files without reading lines, using java?

javatext-filesout-of-memoryoverheadread-write

提问by Chathura Kulasinghe

I am in a situation where I need to join a few very large text files, using a java program.

我处于需要使用 java 程序加入一些非常大的文本文件的情况。

Eg:

例如:

file_01

文件_01

line 01
line 02
line 03

file_02

文件_02

line 04
line 05
line 06

file_03

文件_03

line 07
line 08
line 09

The output file needs to be like,

输出文件需要像,

line 01
line 02
line 03
line 04
line 05
line 06
line 07
line 08
line 09

Is it possible to do this without reading every single line of each file?

是否可以在不读取每个文件的每一行的情况下执行此操作?

采纳答案by Sergey L.

It is not possible to merge two files without reading all the contents (of at lest one of them) and writing it into another file. Filesystems don't support that operation. If you need to merge two files you read them one by one (not necessary a line at a time, but all the contents) and write it into another single file.

如果不读取所有内容(至少其中一个)并将其写入另一个文件,则不可能合并两个文件。文件系统不支持该操作。如果您需要合并两个文件,您可以一个一个读取它们(一次不需要一行,而是所有内容)并将其写入另一个文件。

Edit Example:

编辑示例:

 BufferedReader br(in);
 String line;

 while ((line = br.readLine()) != null) {
      // write it out
 }

回答by lib4

You can use apaches Apache Commons IO library, this has FileUtils class to merge two files. Here s the sample

您可以使用 apaches 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 like 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