How Can I Reset The File Pointer to the Beginning of the File in Java?

前端 未结 10 1502
孤城傲影
孤城傲影 2021-02-19 20:17

I am writing a program in Java that requires me to compare the data in 2 files. I have to check each line from file 1 against each line of file 2 and if I find a match write the

10条回答
  •  北恋
    北恋 (楼主)
    2021-02-19 20:41

    Obviously you could just close and reopen the file like this:

         while((s1=file1.data.readLine())!=null){
             System.out.println("s1: "+s1);
             FileReader file2=new FileReader("d:\\testfiles\\FILE2.txt");
             while((s2=file2.data.readLine())!=null){
                 System.out.println("s2: "+s2);
                 //compare s1 and s2;
             }
             file2.closeFile()
         }
    

    But you really don't want to do it that way, since this algorithm's running time is O(n2). if there were 1000 lines in file A, and 10000 lines in file B, your inner loop would run 1,000,000 times.

    What you should do is read each line and store it in a collection that allows quick checks to see if an item is already contained(probably a HashSet).

    If you only need to check to see that every line in file 2 is in file 1, then you just add each line in file one to a HashSet, and then check to see that every line in file 2 is in that set.

    If you need to do a cross comparison where you find every string that's in one but not the other, then you'll need two hash sets, one for each file. (Although there's a trick you could do to use just one)

    If the files are so large that you don't have enough memory, then your original n2 method would never have worked anyway.

提交回复
热议问题