Home >Java >javaTutorial >Java program to merge the contents of all files in a directory

Java program to merge the contents of all files in a directory

王林
王林forward
2023-08-26 11:37:061321browse

Java program to merge the contents of all files in a directory

To merge the contents of all files in the directory, the Java code is as follows −

Example

import java.io.*;
public class Demo{
   public static void main(String[] args) throws IOException{
      File my_dir = new File("path to place where file is generated");
      PrintWriter my_writer = new PrintWriter("The .txt where changes are stored");
      String[] file_names = my_dir.list();
      for (String file_names : fileNames){
         System.out.println("Content read from " + file_names);
         File my_file = new File(my_dir, file_names);
         BufferedReader my_reader = new BufferedReader(new FileReader(my_file));
         my_writer.println("The file contains " + file_names);
         String my_line = my_reader.readLine();
         while (my_line != null){
            my_writer.println(my_line);
            my_line = my_reader.readLine();
         }
         my_writer.flush();
      }
      System.out.println("All data from files have been read and " + my_dir.getName() + "merged");
   }
}

Output

All file contents will be merged into a single text file.

named Demo The class contains the main function. A new file type will be created and its location The location where the new file needs to be created is passed to it as a parameter.

Create a PrintWriter instance and store the filenames present in the directory in a string array. The file names are iterated and read using BufferedReader instances. Whatever is read will be retained Write new file and store. The writer is also flushed so no residue is left behind.

The above is the detailed content of Java program to merge the contents of all files in a directory. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete