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

There are two text files, whose names are given by two String variables file1 an

ID: 3815133 • Letter: T

Question

There are two text files, whose names are given by two String variables file1 and file2. These text files have the same number of lines. Write a sequence of statements that creates a new file whose name consists concatenating the names of the two text files (with a in the middle) and whose contents of merging the lines of the two files. Thus, in the new file, the first line is the first line from the first file, the second line is the first line from the second file. The third line in the new file is the second line in the first file and the fourth line is the second line from the second file, and so on. When finished, make sure that the data written to the new file has been flushed from its buffer and that any system resources used during the course of running your code have been released.(Do not concern yourself with any possible exceptions here assume they are handled elsewhere.)

Explanation / Answer

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class HelloWorld
{
public static void main(String[] args) throws IOException
{
ArrayList<String> content = new ArrayList<String>();

// taking user input
Scanner sc = new Scanner(System.in);
String a= sc.next();
String b= sc.next();
String s1s2 = a.substring(0,a.indexOf('.'))+"-"+b.substring(0,b.indexOf('.'))+".txt";


try
{
// opening file using bufferedreader
BufferedReader br = new BufferedReader(new FileReader(a));
BufferedReader r = new BufferedReader(new FileReader(b));
String file1content =null;
String file2content = null;

// reading line by line from two files at a time
while ((file1content = br.readLine()) != null && (file2content = r.readLine()) != null)
{   
content.add(file1content);
content.add(file2content);
}
}
catch (IOException e)
{
e.printStackTrace();
}

//opening/creating new file
BufferedWriter wr=null;
wr = new BufferedWriter(new FileWriter(s1s2));
String listWord;

// writing each word to file
for (int i = 0; i< content.size(); i++)
{
listWord = content.get(i);
wr.write(listWord);
wr.write(" ");
}
  
// printing that it is done
System.out.println("Done");

// closing the file
wr.close();
}
}

/*

Sample Input - a.txt

Chegg
India
012

Sample Input - b.txt

Answers
Questions
123

Sample Output

Chegg
Answers
India
Questions
012
123

*/

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