0

I searched for this error on StackOverflow but any topic seens to solve my problem. I have this code that opens a .txt file and inicialize objects variables and this error appears.

public void lerDoArquivo() {
    try {
        FileReader ler = new FileReader("Menu_de_itens.txt");
        BufferedReader reader = new BufferedReader(ler);
        String linha;

        while ((linha = reader.readLine()) != null) {
            processaEntrada(linha);
        }

        reader.close();
    } 
    catch (IOException e) {
        e.printStackTrace();
    }  
}

This is my stracktrace:

Exception in thread "main" java.lang.NullPointerException
    at java.io.FileInputStream.<init>(FileInputStream.java:130)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at ItemMenuDAOTxt.lerDoArquivo(ItemMenuDAOTxt.java:22)
    at ItemMenuDAO.<init>(ItemMenuDAO.java:16)
    at ItemMenuDAOTxt.<init>(ItemMenuDAOTxt.java:14)
    at ControleDeMenu.<init>(ControleDeMenu.java:21)
    at FastFoodOO.main(FastFoodOO.java:11)
Alessio
  • 3,404
  • 19
  • 35
  • 48
Hiago_RaD
  • 41
  • 6
  • 2
    the file is not found: "./resources/Menu_de_itens.txt" – Jeryl Cook Jun 11 '19 at 17:52
  • file not found. read about classpath during runtime and use `getClass().getResource` or `getClassLoader().getResource` or their stream variants – UninformedUser Jun 11 '19 at 17:56
  • 1
    `new FileReader` would only throw `NullPointerException` if you pass in a `null` value. If it was because the file didn't exist, as others have suggested, you'd get `FileNotFoundException`. – Andreas Jun 11 '19 at 17:56
  • I agree with @Andreas. Is there something you didn't post here? – black panda Jun 11 '19 at 18:25
  • As already said, unless you pass in a null parameter value, you shouldn't get that exception. But, if you disagree, why not grab your handy IDE and have a look at line 130 of the source for class `FileInputStream`, to see what that line does, and why it causes NPE? Or, my oh my, step through the code with the IDE's built-in debugger and see for yourself what the values are and what's going on? – Andreas Jun 11 '19 at 20:12
  • Your code leaks resources in the face of exceptions. – Raedwald Jul 23 '19 at 15:30

1 Answers1

0

confirm you can read the file, most likely the file is no found.

 assert new File("./resources/Menu_de_itens.txt").canRead();
Jeryl Cook
  • 989
  • 17
  • 40