Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that opens two text files (input1.txt and input2.txt) for input

ID: 3693160 • Letter: W

Question

Write a program that opens two text files (input1.txt and input2.txt) for
input and one for output (output.txt). The program should merge the two input files in the output files.
While doing the merge, it will read one line from input1.txt and one line from input2.txt
and write those in the output file one after other. Then it will read the next line from input1.txt and
next line from input2.txt and write them one after other in the output file. Here is an example.

input1.txt:

This is the first line in input1.txt.
This is the second line in input1.txt.
This is the third line in input1.txt.
This is the fourth line in input1.txt.

input2.txt:

This is the first line in input2.txt.
This is the second line in input2.txt.
This is the third line in input3.txt.

outtput.txt
This is the first line in input1.txt.
This is the first line in input2.txt.
This is the second line in input1.txt.
This is the second line in input2.txt.
This is the third line in input1.txt.
This is the third line in input3.txt.
This is the fourth line in input1.txt.

After the writing in output.txt, count the number of lines in output.txt.
Also write the number of times term ‘input1’ appears in output.txt file.

Explanation / Answer

import java.util.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.*;
class merge2files
{
   public static void main(String args[])
   {
       int c=0;
       try
       {
           Scanner scan1 = new Scanner(new File("input1.txt"));
           Scanner scan2 = new Scanner(new File("input2.txt"));
           PrintWriter out = new PrintWriter("output.txt");
      
           while(scan1.hasNext() || scan2.hasNext())
           {
               String str1=scan1.nextLine();
               out.println(str1);
                  
               String str2=scan1.nextLine();
               out.println(str2);
          
           }
           out.close();

           Scanner scan3 = new Scanner(new File("output.txt"));
      
           System.out.println("output.txt");
           while(scan3.hasNext())
           {
               String s= scan3.nextLine();
               System.out.println(s);
               c++;
           }

           System.out.println("Total number of lines in output.txt = "+c);
       }
       catch (FileNotFoundException e)
   {
       e.printStackTrace();
       return;
   }
   }
}

      

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote