Home > Java > javaTutorial > body text

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

王林
Release: 2023-08-26 11:37:06
forward
1258 people have browsed it

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");
   }
}
Copy after login

Output

All file contents will be merged into a single text file.
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!