Reputation: 23
I am trying to read in a .txt file into java. Regardless if it ends on a blank line or not, the reader will not read in the last line, and the program won't terminate.
public static ArrayList<String> readInput() {
// TODO Auto-generated method stub
ArrayList<String> input = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
// while (scanner.hasNextLine()) {
// String line = scanner.nextLine();
// if (line.equals("") || line.isEmpty()) {
// break;
// }
// input.add(line);
// System.out.println(line);
// }
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
while((line = reader.readLine()) != null && !line.isEmpty()) {
input.add(line);
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null,"File not found or is unreadable.");
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//PROGRAM WILL NOT GO BEYOND THIS POINT.
JOptionPane.showMessageDialog(null,"File has finished reading.");
return input;
Here, I tried two methods. One with a buffered reader, and the other with a scanner, but neither works. Here is a snippet of the .txt file:
...some more lines...
33
0 0 0
1 0 0
0 1 0
34
0 0 0
1 0 0
1 0 0
35
0 1 0
0 1 0
0 0 1
36
1 0 0
0 1 0
0 1 0
The program will read up to the second last line. So this'll be what i see:
...some lines...
0 0 1
36
1 0 0
0 1 0
and the program will still be running. It won't even re-enter the while loop (i tested it with a println).
Even if i was to add a blank line after the last line like so:
...some lines...
0 0 1
36
1 0 0
0 1 0
0 1 0
<a blank line>
The program will read up to the last line of numbers, be unable to re-enter the loop, and the program will not terminate.
...some lines...
0 0 1
36
1 0 0
0 1 0
0 1 0
I've tried looking everywhere for solutions but can't seem to find one that actually solves this issue.
Preferably, I would like to follow scenario 1 where I do not end the text file with a blank line.
also each line of the .txt file ends on a new line, and contains no trailing white spaces. Thanks!
Upvotes: 0
Views: 371
Reputation: 139
You need an EOF character in order for your program to terminate. Try typing CTRL-D in your console, that will end the execution.
Upvotes: 0