Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Merging elements of two different arrays alternatively in third array
Next article icon

Java program to merge two files alternatively into third file

Last Updated : 30 May, 2018
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite : PrintWriter , BufferedReader

Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt but merging should be done by line by line alternatively. The following are steps to merge alternatively.

  1. Create PrintWriter object for file3.txt
  2. Open BufferedReader for file1.txt
  3. Open BufferedReader for file2.txt
  4. Run a loop to copy each line of file1.txt and then file2.txt to file3.txt
  5. Flush PrintWriter stream and close resources.

To successfully run the below program file1.txt and file2.txt must exits in same folder OR provide full path for them.




// Java program to merge two 
// files  into third file alternatively
  
import java.io.*;
  
public class FileMerge 
{
    public static void main(String[] args) throws IOException 
    {
        // PrintWriter object for file3.txt
        PrintWriter pw = new PrintWriter("file3.txt");
          
        // BufferedReader object for file1.txt
        BufferedReader br1 = new BufferedReader(new FileReader("file1.txt"));
        BufferedReader br2 = new BufferedReader(new FileReader("file2.txt"));
          
          
        String line1 = br1.readLine();
        String line2 = br2.readLine();
          
        // loop to copy lines of 
        // file1.txt and file2.txt 
        // to  file3.txt alternatively
        while (line1 != null || line2 !=null)
        {
            if(line1 != null)
            {
                pw.println(line1);
                line1 = br1.readLine();
            }
              
            if(line2 != null)
            {
                pw.println(line2);
                line2 = br2.readLine();
            }
        }
      
        pw.flush();
          
        // closing resources
        br1.close();
        br2.close();
        pw.close();
          
        System.out.println("Merged file1.txt and file2.txt 
alternatively into file3.txt");
    }
}
 
 

Output:

  Merged file1.txt and file2.txt into file3.txt  

Note : If file3.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created.



Next Article
Merging elements of two different arrays alternatively in third array

G

Gaurav Miglani
Improve
Article Tags :
  • Java
  • array-merge
  • java-file-handling
  • Java-I/O
Practice Tags :
  • Java

Similar Reads

  • Java program to merge two files into a third file
    Prerequisite : PrintWriter , BufferedReader Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt. The following are steps to merge. Create PrintWriter object for file3.txt Open BufferedReader for file1.txt Run a loop to copy each line of f
    2 min read
  • Java program to delete duplicate lines in text file
    Prerequisite : PrintWriter , BufferedReader Given a file input.txt . Our Task is to remove duplicate lines from it and save the output in file say output.txt Naive Algorithm : 1. Create PrintWriter object for output.txt 2. Open BufferedReader for input.txt 3. Run a loop for each line of input.txt 3.
    3 min read
  • Java program to delete certain text from a file
    Prerequisite : PrintWriter , BufferedReader Given two files input.txt and delete.txt. Our Task is to perform file extraction(Input-Delete) and save the output in file say output.txt Example : Naive Algorithm : 1. Create PrintWriter object for output.txt 2. Open BufferedReader for input.txt 3. Run a
    3 min read
  • Merging elements of two different arrays alternatively in third array
    Given two arrays arr1[] and arr2[], we need to combine two arrays in such a way that the combined array has alternate elements of both. If one array has extra element, then these elements are appended at the end of the combined array. Input : arr1[] = {1, 2, 3, 4, 5, 6} arr2[] = {11, 22, 33, 44}Outp
    7 min read
  • Javascript Program to Merge 3 Sorted Arrays
    Given 3 arrays (A, B, C) which are sorted in ascending order, we are required to merge them together in ascending order and output the array D. Examples: Input : A = [1, 2, 3, 4, 5] B = [2, 3, 4] C = [4, 5, 6, 7] Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7] Input : A = [1, 2, 3, 5] B = [6, 7, 8
    8 min read
  • Java program to store a Student Information in a File using AWT
    Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications.
    4 min read
  • Read File Into an Array in Java
    In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method. To store the content of the file better use the collection storage type instead of a static array as we don't know the exact lines o
    8 min read
  • Files createTempDirectory() Method in Java with Examples
    The createTempDirectory() method of java.nio.file.Files Class is used to create a new directory using the given prefix and attributes. The given prefix acts as the name of the formed directory, may be null. The directory is set with given attributes. Based on the type of arguments passed, the Files
    4 min read
  • How to Create and Modify Properties File Form Java Program in Text and XML Format?
    Properties file are a text-oriented key value a pair of contents present in a Java project with .properties extension. Line by line, the key-value pair of contents are present, and they are usually prepared by means of notepad, Wordpad, EditPlus, etc., Properties files are usually helpful to store i
    5 min read
  • Create a Temporary File in Java
    In Java, we can create a temporary file using an existing method known as File.createTempFile() method which creates a new empty file on the specified directory. The createTempFile() function creates a temporary file in a given directory (if the directory is not mentioned then a default directory is
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences