Create a MergeFiles application that merges the integers ordered from low to hig
ID: 3794648 • Letter: C
Question
Create a MergeFiles application that merges the integers ordered from low to high in two text data files into a third text data file, maintaining the order from low to high (no post merge sorts!). For example, the two files of integers could contain:
File 1: 12 23 34 45 56 67 69 123 133
File 2: 4 5 10 20 35 44 100 130 150 160 180
The application should not use an array or ArrayList to temporarily store the numbers, but should merge the two files taking one element at a time from each. After MergeFiles runs for this example, the third file should contain:
4 5 10 12 20 23 34 35 44 45 56 67 69 100 123 130 133 150 160 180
Create the two input files using a text editor with the numbers of your choice. Be sure to employ proper exception handling for the file I/O. Use at least one try-catch statement that properly handles exceptions.
Explanation / Answer
Hi, Please find my implementation.
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class MergeFiles {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first input file name: ");
String firstFile = sc.next();
System.out.print("Enter second input file name: ");
String secondFile = sc.next();
System.out.print("Enter output file name: ");
String outputFile = sc.next();
try{
// opening both input file
Scanner readFileOne = new Scanner(new File(firstFile));
Scanner readFileTwo = new Scanner(new File(secondFile));
// Opening file writer
PrintWriter writeFile = new PrintWriter(new File(outputFile));
// creating two array list
ArrayList<Integer> firstArr = new ArrayList<>();
ArrayList<Integer> secondArr = new ArrayList<>();
// reading first file
while(readFileOne.hasNextInt()){
firstArr.add(readFileOne.nextInt());
}
// reading second file
while(readFileTwo.hasNextInt()){
secondArr.add(readFileTwo.nextInt());
}
// printing both list
System.out.println(firstArr);
System.out.println(secondArr);
// merging two array and writing to file
int i=0, j=0;
while(i<firstArr.size() && j<secondArr.size()){
if(firstArr.get(i) <= secondArr.get(j)){
writeFile.print(firstArr.get(i)+" ");
i++;
}else{
writeFile.print(secondArr.get(j)+" ");
j++;
}
}
// writing remaining entries of firtArr or secondArr
while( i < firstArr.size()){
writeFile.print(firstArr.get(i)+" ");
i++;
}
while( j < secondArr.size()){
writeFile.print(secondArr.get(j)+" ");
j++;
}
// closing all files
sc.close();
readFileOne.close();
readFileTwo.close();
writeFile.close();
System.out.println("File Written Successfully!!!");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
/*
Sample run:
Enter first input file name: file1.txt
Enter second input file name: file2.txt
Enter output file name: mergedfile.txt
[12, 23, 34, 45, 56, 67, 69, 123, 133]
[4, 5, 10, 20, 35, 44, 100, 130, 150, 160, 180]
File Written Successfully!!!
*/