javabufferedreader

BufferedReader returning null when reading a file that isn't empty


Each file has one line with one letter. Why are both are returning null?

File saveFile = new File("saved.txt");
File pocFile = new File("playerOrComputer.txt");

if (!pocFile.exists()) {
    pocFile.createNewFile();
}
if (!saveFile.exists()) {
    saveFile.createNewFile();
}   

BufferedReader brPoC = new BufferedReader(new FileReader(pocFile));
BufferedReader brSave = new BufferedReader(new FileReader(saveFile));

String savedChar = brSave.readLine();
brSave.close();
String playerOrComputerChar = brPoC.readLine();
brPoC.close();

System.out.println(savedChar);
System.out.println(playerOrComputerChar);

Solution

  • Try the while loop while reading using BufferedReader:

    while ((savedChar = brSave.readLine()) != null) {
        System.out.println(savedChar);
    }
    

    If your files Contains text it will definitely show:

    Do not also leave the BufferedReader Open. Once you are done reading Close it:

    if (brSave != null)br.close();