Try this:
public static void readFiles(String fileString)
throws FileNotFoundException {
File file = new File(fileString);
Scanner scanner = null;
String line = "";
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
return;
}
Boolean started = false;
while (scanner.hasNext()) {
line = scanner.nextLine();
if (line.equals("BGEND")) {
started = false;
}
if (started)
{
System.out.println(line);
lb1.append(line);
window2.add(lb1);
}
if (line.equals("BGSTART")) {
started = true;
}
}
scanner.close();
}
How does it work?
- It goes through the lines.
- It the line equals
BGEND
, it sets started
to false. - If
started
equals true
, it performs the actions with the line such as printing it. - If the line equals
BGSTART
, it sets started
to true.
The order of these steps is important, because BGSTART and BGEND don't have to be printed themselves.
Some other changes:
- In the catch block, you should return, because if you don't, the method continues without the scanner is created.
- The scanner should be closed at the end.