In: Computer Science
Create two files, file1.csv and file2.csv
Write the following information in file1.csv:
Apple 1.69 001
Banana 1.39 002
Write the following information in file2.csv:
Apple 1.69 001
Carrot 1.09 003
Beef 6.99 004
You have two files, both of the two files have some information about products: • Read these two files, find out which products exist in both files, and then save these products in a new file. You can use the two files you created in Lab 1 as an example. If you use file1.csv and file2.csv from Lab 1, the result file will be:
•Result file:
Apple 1.69 001
JAVA Program to read two files, finding similar products that exist in both files and save it in a new file :
import java.io.File;//Importing all required modules
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Scanner;
class JavaEg {
public static void main(String[] args) throws IOException {
Scanner input1 = new Scanner(new File("file1.csv"));//reading first file
Scanner input2 = new Scanner(new File("file2.csv"));//reading second file
while(input1.hasNextLine() && input2.hasNextLine()){
String first_file = input1.nextLine(); //reading lines on first file
String second_file = input2.nextLine(); //reading lines on second file
if(first_file.equals(second_file)){ //comparing lines of both files
System.out.println("Similarities found: "+"\n"+first_file);
String content = first_file+"\n";
String path = "File3.csv"; //path of new output file
try { //using try to write
Files.write(Paths.get(path), content.getBytes(), StandardOpenOption.APPEND); //writing similar contents to anew output file
}catch (IOException e) { // using catch for exception
}
}
}
}
}
File 1:
File 2:
Output File3:
The answer have been updated in Java language.