I am reading a set of integer values in from a .txt file in Java using Scanner and FileReader. There is one value per line in the input file. All of the values are read into the StringBuilder variable, but for some reason the compiler throws an exception right at the end of reading the input in the while loop and I can't quite figure out why.
Scanner inFile;
String value = "";
String arrayString = "";
StringBuilder sb = new StringBuilder();
try {
inFile = new Scanner(new FileReader("data.txt"));
value = inFile.next();
while (inFile.hasNextLine()) {
sb.append(value);
value = inFile.next();
}
arrayString = sb.toString(); // Not executing
System.out.println(arrayString); // Not executing
inFile.close();
} catch (Exception e) {
System.out.println("Error: File not found.");
} finally {
// inFile.close();
}
System.out.println(arrayString); // Not executing
scanner.hasNextLine()andscanner.nextLine()ORscanner.hasNext()andscanner.next(), but don't mix them. Empty lines can cause issues like the one you're having.