Answer:
Check the explanation
Step-by-step explanation:
Steps to follow:-
Read file1 or file2
Get number from line of file1
Check numberlist contains this number
if number is not in numberlist then add number to numberlist
Write line of file1 to outputFile
Read file2
Get number from line of file2
Check numberlist contains this number
if number is not in numberlist then add number ot numberlist
Write line of file2 to outputFile
Repeat the above process untill file line is not null
Complete Java code:-
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args)
{
mergerFiles();
}
public static void mergerFiles()
{
try {
FileReader fileReader1 = new FileReader("res/file1");
BufferedReader bufferedReader1 = new BufferedReader(fileReader1);
FileReader fileReader2 = new FileReader("res/file2");
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
FileWriter fileWriter = new FileWriter("res/outputfile");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String file1Line=null;
String file2Line=null;
Set<String> set=new HashSet();
while(((file1Line = bufferedReader1.readLine()) != null) || (file2Line = bufferedReader2.readLine())!= null) {
String number1=file1Line.split(",")[0].split(":")[1];
if(set.add(number1))
{
bufferedWriter.write(file1Line+"\\");
}
if((file2Line = bufferedReader2.readLine())!= null) {
String number2 = file2Line.split(",")[0].split(":")[1];
if (set.add(number2)) {
bufferedWriter.write(file2Line+"\\");
}
}
}
bufferedWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
File1 content:-
number:1234567890, lastname: Kumar, address: delhi, property:2000 sqft
number:2234567890, lastname: Chaudhari, address: Pune, property:4000 sqft
number:3234567890, lastname: Singh, address: Mumbai, property:2500 sqft
number:4234567890, lastname: Varma, address: Kolkata, property:5000 sqft
number:5234567890, lastname: Sinha, address: Patna, property:6000 sqft
File2 content:-
number:4234567890, lastname: Ram, address: bangalore, property:25000 sqft
number:6234567890, lastname: Rajput, address: Ranchi, property:40400 sqft
number:3234567890, lastname: Sinha, address: Gurgaon, property:25300 sqft
number:4234567890, lastname: Kaur, address: Chennai, property:50200 sqft
number:8234567890, lastname: Mehta, address: Pondicherry, property:26000 sqft
Output file content:-
number:1234567890, lastname: Kumar, address: delhi, property:2000 sqft
number:4234567890, lastname: Ram, address: bangalore, property:25000 sqft
number:2234567890, lastname: Chaudhari, address: Pune, property:4000 sqft
number:6234567890, lastname: Rajput, address: Ranchi, property:40400 sqft
number:3234567890, lastname: Singh, address: Mumbai, property:2500 sqft
number:5234567890, lastname: Sinha, address: Patna, property:6000 sqft
number:8234567890, lastname: Mehta, address: Pondicherry, property:26000 sqft