Reputation:
I am writing a file IO method and have a while loop within a try/catch clause. Thus works though my txt file that I am reading must have a new blank line at the end in order for it to work corrctly. If the txt file does not have this blank line then it runs but also produces my catch exception error msg at the end.
Any ideas on how to implement a NoSuchElementException to fix this.
Thanks
Upvotes: 1
Views: 54
Reputation:
replace
String line = reader.readLine();
while(line.length() > 0) {
System.out.println(line);
line = reader.readLine();
}
with
String s;
while((s = reader.readLine()) != null) {
System.out.println(s);
}
Upvotes: 1
Reputation: 149
Change the whileloop to:
while((line = reader.readLine()) != null){
Sysout...
}
And it will work. Problem with your code is, that you read a line and than enter the whileloop again.
Upvotes: 3
Reputation: 3423
Scanner in = new Scanner(filename);
File fileName = new File(filename);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch(Exception e) {
System.out.println("ERROR FILE NOT FOUND");
in.close(); // close scanner if file not found
}
Upvotes: 1