Search code examples
javatext-filesout-of-memoryoverheadread-write

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


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

Eg:

file_01

line 01
line 02
line 03

file_02

line 04
line 05
line 06

file_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?


Solution

  • 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
     }