Search code examples
javanullpointerexceptionbufferedreaderfileinputstream

BufferedReader returning Null for no apparent reason


and thanks in advance for help. I am pretty new to Java and haven't had any formal Java education. I am making a Minecraft Bukkit server for practice and am logging sign locations to a file when created. I am trying to make a boolean that returns true if the location is already in the file and false if it isn't. I can't use a while loop or else it freezes the server so I am using a for loop. Anyways, all of the lines that the BufferedReader returns are null and I don't know why. I have an integer that returns the numbers of lines in a file using BufferedReader that works fine. I don't see why it is returning null with the boolean. Here is the boolean:

code Block :

    private boolean isDuplicate(String in) throws IOException
    {
        File f = file;
        try {
            fr = new FileReader(f);
            br = new BufferedReader(fr);
        } catch (FileNotFoundException e1) {
            log(Level.WARNING, "File not found.");
        }
        String temp;
        in = in.substring(0,in.length() - 1);
        for(int i = 0; i < (countLines(f)); i++)
        {
            if((temp = br.readLine()) != null)
            {
                String s = temp;
                log(temp);
            }
        }
        return false;
    }

Here is the integer:

    private int countLines(File f){
        try {
            fr = new FileReader(f);
            br = new BufferedReader(fr);
        } catch (FileNotFoundException e1) {
            log(Level.WARNING, "File not found!");
        }

        for(int i = 0; i < 100000; i++)
        {
            try
            {
                if(br.readLine() == null)
                {
                    return i;
                }
            }
            catch (NullPointerException e)
            {
                return i;
            }
            catch (IOException e)
            {

            }
        }
        return 0;
    }

Solution

  • The 'apparent reason' is that you have reached the end of the file. But this code is nonsense. You don't need to count the lines in advance at all, and you certainly don't need to count them every time around the loop, which is what your current code does. At present your processing is O(N2), which is disastrous. Just call readLine() until it returns null:

    while ((line = br.readLine()) != null)
    {
        // ...
        log(line);
    }
    

    NB There is no way that your isDuplicate() method does anything even slightly resembling its name.