Skipping every other line while importing Strings from a .txt file in Java

Viewed 238

I'm attempting to import Strings from a .txt file with 50,000 rows. Every single row in the txt file has exactly one string with all under-case letters and no spaces in between the letters. The code I've written below is working, but there is one strange issue, it skips every other row of the .txt file (specifically the even-numbered rows). If any one could help me identify where I've gone wrong, it would be much appreciated.

import java.awt.List;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;

public class WordRecommender {

StringBuilder sb = new StringBuilder();
               String strLine = "";
               ArrayList<Word> objectArray = new ArrayList<Word>();
               try {
                    BufferedReader br = new BufferedReader(new FileReader("engDictionary.txt"));
                     while (strLine != null)
                      {
                       strLine = br.readLine();
                       sb.append(strLine);
                       sb.append(System.lineSeparator());
                       strLine = br.readLine();
                       if (strLine==null)
                          break;
                       objectArray.add(new Word(strLine));
                   }
                    br.close();
               } catch (FileNotFoundException e) {
                   System.err.println("File not found");
               } catch (IOException e) {
                   System.err.println("Unable to read the file.");
               }
import java.util.ArrayList;

public class Word {

    String wordName;
    ArrayList<Character> uniqueLetters;

    public Word(String string) {
        ArrayList<Character> tempArray = new ArrayList<Character>();

        for (int i = 0; i < string.length(); i++) { 
                        tempArray.add(string.charAt(i));
                    }

        this.wordName = string;
        this.uniqueLetters = tempArray;
}
1 Answers

Inside while loop, you are reading 2 lines and appending only one. You can do this instead:

while (strLine != null) {
    strLine = br.readLine();
    if (strLine==null)
        break;
    sb.append(strLine);
    sb.append(System.lineSeparator());
    objectArray.add(new Word(strLine));
}
Related