Java – Use Java.IO to merge all .txt files in a folder

Use Java.IO to merge all .txt files in a folder… here is a solution to the problem.

Use Java.IO to merge all .txt files in a folder

I’m trying to merge all .txt files into a specific folder and create one output.txt file.
I’m new to Java and learning Java.IO packages.
Here is my program that compiles nicely and creates an output file, but doesn’t write anything to it.
I verified the text file I entered and it has data.

import java.io.*;

class  Filemerger
{
    public static void main(String[] args) throws IOException
    {
        PrintWriter pw = new PrintWriter("true1.txt");      
        File f = new File("E:\\A");
        String[] s = f.list();
        for (String s1 : s)
        {
            File f1 = new File(f, s1);
            BufferedReader br = new BufferedReader(new FileReader(f1));
            String line = br.readLine();
            while (line != null)
            {
                pw.println(line);
                line = br.readLine();
            }
        }
        pw.flush();
        pw.close();
    }
}

Solution

I think your mistake is minor, maybe some path is wrong or something like that. Regardless, you should use a new IO API called NIO to interact with files. The key classes are Paths and Files located in package java.nio.

class  Filemerger
{
    public static void main(String[] args) throws IOException
    {
        Path output = Paths.get("true1.txt");
        Path directory = Paths.get("E:\\A");
        Stream<Path> filesToProcess = Files.list(directory);

 Iterate all files
        filesToProcess.forEach(path -> {
             Get all lines of that file
            Stream<String> lines = Files.lines(path);
             Iterate all lines
            lines.forEach(line -> {
                 Append the line separator
                String lineToWrite = line + System.lineSeparator();

 Write every line to the output file
                Files.write(output, lineToWrite.getBytes(StandardCharsets.UTF_8));
            });
        });
    }
}

Alternatively, if you only want to collect all rows of all files without mapping the files to which they belong, you can also use the Stream#flatMap method:

Path output = Paths.get("true1.txt");
Path directory = Paths.get("E:\\A");

Files.list(directory)
    .flatMap(Files::lines)
    .forEach(line -> {
        Files.write(output, (line + System.lineSeparator())
            .getBytes(StandardCharsets.UTF_8));
    });

Note that Files#write and other methods also accept a range of options that you can set. For example, if the file does not already exist, you should create it. Or, if it already exists, whether the content should be attached or the old content deleted.

So check out the documentation page:

Related Problems and Solutions