In this post under Java I will with example how to merge two or more text files.
Below is the complete code for your reference
Main class
1 package io;
2
3 import java.io.*;
4
5 public class IOExample3 {
6 private static int BYTES_TO_BE_READ = 1000;
7 private char buffer[] = new char[BYTES_TO_BE_READ];
8
9 public static void main(String[] args) throws IOException {
10 if(args.length == 0 || args.length < 3) {
11 throw new IllegalArgumentException("Destination file name and more then one source file name should be entered");
12 }
13 IOExample3 ioExample3 = new IOExample3();
14 ioExample3.merge(args);
15 }
16
17 public void merge(String[] args) throws IOException {
18 String destFileName = args[0];
19 File destFile = new File(destFileName);
20 try(FileWriter fileWriter = new FileWriter(destFile);
21 BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
22 for(int i = 1; i < args.length; i++) {
23 File file = new File(args[i]);
24 try(FileReader fileReader = new FileReader(file);
25 BufferedReader bufferedReader = new BufferedReader(fileReader)) {
26 int bytesRead = bufferedReader.read(buffer, 0, BYTES_TO_BE_READ);
27 while(bytesRead != -1) {
28 bufferedWriter.write(buffer, 0, bytesRead);
29 bytesRead = bufferedReader.read(buffer, 0, BYTES_TO_BE_READ);
30 }
31 }
32 }
33 }
34 }
35 }
In the above main method, I am asking the destination file name and more than one source file name to be merged as command line arguments.
If none of them is provided we throw “IllegalArgumentException” exception.
At line 13, I create an instance of “IOExample3” class.
At line 14, I call “IOExample3” instance method “merge” and pass the command line arguments as it is.
In the “merge” method code, at line 18, retrieving the destination file name and saying it “destFileName” variable.
At line 19, creating a “File” instance for destination file.
In the try block at line 20, created an instance of “BufferedWriter” to write to the destination file.
Then in a loop,
1) opening every source file one after another in the order provided by the user
2) for every source file opened, we read the data and write to the destination file in an inner loop until the EOF of the source file is reached.
In this way we can merge multiple text files.