javabufferedreaderprintwriter

Comparing two text files in random order with Java


I am trying to compare two text files that are randomized and print out the lines that match in both of the files. File 1:

Student1
Student2
Student3
Student4

File 2:

Student6
Student1
Student2

I want the output as

Student1
Student2

My code is below.

public static void main(String[] args) throws IOException {

     String first = "file1.txt";
     String second = "file2.txt";
     BufferedReader fBr = new BufferedReader(new FileReader(first));
     BufferedReader sBr = new BufferedReader(new FileReader(second));   




     PrintWriter writer = new PrintWriter("test.txt", "UTF-8");  
     while ((first = fBr.readLine()) != null) {
         String partOne1 = fBr.readLine();
         String partTwo1 = sBr.readLine();
         while ((second = sBr.readLine()) != null) {
                System.out.println(first);
                writer.println(first);  
                break;                   

         }
     }


     writer.close();
     fBr.close();
     sBr.close(); 

Solution

  • It's quite simple=) Try to store all results from first file and compare with all lines from second. It will be like this:

    package com.company;
    
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    
    public class Main {
    
        public static void main(String[] args) throws IOException {
    
            String first = "file1.txt";
            String second = "file2.txt";
            BufferedReader fBr = new BufferedReader(new FileReader(first));
            BufferedReader sBr = new BufferedReader(new FileReader(second));
    
            ArrayList<String> strings = new ArrayList<String>();
    
            while ((first = fBr.readLine()) != null) {
                strings.add(first);
            }
            fBr.close();
    
            while ((second = sBr.readLine()) != null) {
                if (strings.contains(second)) {
                    System.out.println(second);
                }
            }
            sBr.close();
        }
    }
    

    It's better to use memory when possible, your 'while' inside different while can work too long time and obfuskate logic.