
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to merge contents of all the files in a directory
To merge contents of all the files in a 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.
A class named Demo contains the main function. A new file type is created and the location of the place where the new file needs to be created is passed as parameter to it.
A PrintWriter instance is created and names of files present in the directory is stored in a string array. The file names are iterated over, and read using BufferedReader instance. Whatever is read is written into the new file and stored. The Writer is also flushed so that no residue is left out.
- Related Questions & Answers
- Java program to delete all the files in a directory recursively (only files)
- Java program to List all files in a directory recursively
- Java program to List all files in a directory and nested sub-directory - Recursive approach
- Merge contents of two files into a third file using C
- How to list all files in a directory using Java?
- How to list all files (only) from a directory using Java?
- C Program to list all files and sub-directories in a directory
- How to read data from all files in a directory using Java?
- Java program to merge two files into a third file
- How to list out the hidden files in a Directory using Java program?
- Python - How to Merge all excel files in a folder
- How to delete all files in a directory with Python?
- How to unzip all zipped files in a Linux directory?
- How to Copy the entire contents of a directory in C#?
- How do I list all files of a directory in Python?
Advertisements