I have created a method for reading a file in Java. The file in question contains a list of books with the following format: lastname|firstname|title. However, when I try to use the method I get an error message. My method is as follows:
private final static char END_SIGN = '|';
void readBookFile(String readFile) {
try {
FileReader textFileReader = new FileReader(readFile);
BufferedReader textReader = new BufferedReader(textFileReader);
int numberOfBooks = Integer.parseInt(textReader.readLine());
for (int i = 0; i < numberOfBooks; i++) {
String post = textReader.readLine();
int index1 = post.indexOf(END_SIGN);
int index2 = post.indexOf(END_SIGN, index1 + 1);
String lastname = post.substring(0, index1);
String firstname = post.substring(index1 + 1, index2);
String title = post.substring(index2 + 1);
Book book = new Book(lastname, firstname, title);
addBook(book);
}
tekstReader.close();
}
catch (IOException exception) {
System.out.print("Wrong file reading: " + exception);
System.exit(1);
}
}
When I try to run this method I get the error message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Twain|Mark|The Adventures of Huckleberry Finn"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Library.readBookFile(Library.java:36)
at LibraryTest.main(LibraryTest.java:8)
Line 36 is the part of the method where I identify the integer numberOfBooks. So obviously this is not working for some reason. If anyone knows what could cause this, I would greatly appreciate it!
Instead of this code:
Try this:
Also, like Jon Skeet suggests, you should rearrange your code to ensure that the input is closed even if the processing of the input throws an exception. (A
try ... finallyconstruct is good for this.)