- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 two files into a third file
Following is the Java program to merge two files into a third file −
Example
import java.io.*; public class Demo { public static void main(String[] args) throws IOException { PrintWriter my_pw = new PrintWriter("path to third .txt file"); BufferedReader my_br = new BufferedReader(new FileReader("path to first .txt file")); String my_line = my_br.readLine(); while (my_line != null) { my_pw.println(my_line); my_line = my_br.readLine(); } my_br = new BufferedReader(new FileReader("path to second .txt file")); my_line = my_br.readLine(); while(my_line != null) { my_pw.println(my_line); my_line = my_br.readLine(); } my_pw.flush(); my_br.close(); my_pw.close(); System.out.println("The first two files have been merged into the third file successfully."); } }
Output
The first two files have been merged into the third file successfully.
A class named Demo contains the main function. Here an instance of the PrintWriter class and BufferedReader is generated. Every line in the two files is read, until it reaches null. It is then added to the third file, and the class instances are flushed and closed.
Advertisements