Search code examples
javabufferedreaderfileinputstream

BufferedReader not fully reading a file


I have a file with 50 lines, each line just containing one word, and I have the following class to read a random line from the file:

public class WordGenerator{
    static Random generator;

    static int numberGenerator(){
        generator = new Random();
        return generator.nextInt(50)+1; 
    }

    static String wordSelector(){
        String word = null;
        FileInputStream fis = null;
        BufferedReader br = null;
        String temp = String.format("..%sutil%s", File.separator, File.separator);

        try{
            fis= new FileInputStream(temp + "Words.txt");
            br = new BufferedReader(new InputStreamReader(fis));
        }catch(FileNotFoundException ex){
            System.out.println("File not found: " + ex);
        }

    
        try{
            for(int i = 0; i < numberGenerator(); ++i){
                word = br.readLine();
            }
        }catch(IOException e){
            System.out.println("Error in line reading: " + e);
        }

        System.out.println(word);

        return word;
    }
}

The problem is that for some reason the class is never returning anything that is located after the first 5-10 lines and just keeps returning the first ones.

What could be causing this?


Solution

  • Your loop calls numberGenerator() on every iteration. This means that instead of picking a single random number from 1 to 50, you're drawing a new one each time through the loop.

    By the time you get through 5 or 10 iterations, it's likely you've drawn a random number less than i.

    While you're fixing that, move the new Random() instantiation outside of that method. You only need one random number generator, and you can keep calling nextInt() on it. You're needlessly creating a new object every time.