Please understand that reading and writing to a file simultaneously using a BufferedReader/Writer is not really a good idea.
When using a Buffered reader or writer there is no guarantee when the actual reading and writing will be done.
That being said, one fix is to set a mark on the reader before reaching the end of file and also closing (or at least flushing) the output stream. This will force the BufferedWriter to actually write the contents to the file system and allow the reader to read the new content.
Note: You may find that on some file systems this approach will not work.
rea.mark(4048); // Set mark at beginning of file
if (rea.readLine() == null) {
for (int i = 1; i < 6; i++) {
writ.write("Player" + i + "\t\t" + "99:99");
writ.newLine();
}
writ.close();
rea.reset();
}
That being said, I think a better approach would be to check the length and existence of the file before trying to read from it. Please see the sample below.
File file = new File("points.txt");
// checking if file is empty, so it enters imaginary players and scores
// if it is.'
if ((!file.exists()) || (file.length() == 0)) {
try (BufferedWriter writ = new BufferedWriter(new FileWriter(file))) {
for (int i = 1; i < 6; i++) {
writ.write("Player" + i + "\t\t" + "99:99");
writ.newLine();
}
}
// writ is closed by the try()
}
try (BufferedReader rea = new BufferedReader(new FileReader(file))) {
ArrayList<String> top = new ArrayList<String>();
String readthis;
while ((readthis = rea.readLine()) != null) {
top.add(readthis);
}
}
// rea is safely closed by the try()
The stream creation has been put in try() blocks so that they are safely cleaned up.
I hope this helps.