You are here:

Java/Compare alternate lines in txt file in Java

Advertisement


Question
I have a text file that stores hash values generated when hashing files. They are stored line by line with the file name followed by its hash value. For example, my md5.txt contains the following:
File: file.doc
Hash: 8fa42a2b871cb49f7b06481bf12a401d
File: file-copy.doc
Hash: 8fa42a2b871cb49f7b06481bf12a401d

The hash values are on lines 2 and 4 and therefore, I would like to compare alternate lines. Is there a way to do so? What steps should I take to start writing my codes. For example, I would firstly read in the file using BufferedReader and then?

Answer
Let's say you want to determine if there are any potentially duplicate files if your hash text file.

Then you could do something like:



//This try will auto close the reader when your done. Only works in Java 7 and above
try(BufferedReader reader = new BufferedReader(...)) {
  String nextLine;
  HashMap<String, String> hashes = new HashMap<>();
  while((nextLine = reader.readLine()) != null) {
     String fileName = nextLine;
     if(fileName.startsWith("File: ") {
        fileName = fileName.substring("File: ".length());
     }
     else {
        //oops not a proper formatted file
        ...
     }
     String hash = reader.readLine();
     if(hash == null) {
        //oops unexpected end of file
        ...
     }
     if(hash.startsWith("Hash: ") {
        hash = hash.substring("Hash: ".length());
     }
     else {
        //oops not a proper formatted file
        ...
     }
     if(hashes.containsKey(hash) {
        String previousFile = hashes.get(hash);
        //previousFile and fileName have matching hashes
        ...
     }
     else {
        hashes.put(hash,fileName);
     }
  }
}

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.