0
public class Loan {
private Borrower Borrower;
private Book Book;
private LocalDate issueDate;
private LocalDate returnDate;
private int status;
public Loan(Borrower Borrower, Book Book, LocalDate issueDate, LocalDate returnDate, int status) {
this.Borrower = Borrower;
this.Book = Book;
this.issueDate = issueDate;
this.returnDate = returnDate;
this.status = status;
}
public LocalDate getIssueDate() {
return issueDate;
}
public void setIssueDate(LocalDate issueDate) {
this.issueDate = issueDate;
}
public LocalDate getReturnDate() {
return returnDate;
}
public void setReturnDate(LocalDate returnDate) {
this.returnDate = returnDate;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Borrower getBorrower() {
return Borrower;
}
public void setBorrower(Borrower Borrower) {
this.Borrower = Borrower;
}
public Book getBook() {
return Book;
}
public void setBook(Book Book) {
this.Book = Book;
}
}
ArrayList<Loan> Loans= new ArrayList();
try {
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\NimraArif\\Documents\\NetBeansProjects\\ooad1\\src\\ooad1\\Loans.txt"));
String line = null;
int bookid, status, borrowerid;
line = reader.readLine();
while (line!= null) {
String[] values = line.split(",");
bookid = Integer.valueOf(values[0]);
borrowerid=Integer.valueOf(values[1]);
DateTimeFormatter formatter= DateTimeFormatter.ofPattern("dd/MM/yy");
LocalDate issueDate=LocalDate.parse(values[2],formatter);
LocalDate returnDate=LocalDate.parse(values[3],formatter);
status=Integer.valueOf(values[4]);
Book temp = null;
Borrower temp2 = null;
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookid()==bookid) {
temp=Books.get(i);
}
}
for (int i = 0; i < borrowers.size(); i++) {
if (borrowers.get(i).getRollno()==borrowerid) {
temp2=borrowers.get(i);
}
}
Loan temp3 = new Loan(temp2, temp, issueDate, returnDate, status);
Loans.add(temp3);
line = reader.readLine();
}
reader.close();
}
catch (Exception e) {
System.err.format("Exception occurred trying to read '%s'.", "Loans.txt");
e.printStackTrace();
}
當我執行此代碼時,它會在包含解析函數的同時在該行引發異常。但是,如果我自己硬編碼字符串,它工作正常。我不明白爲什麼會發生這種情況。從文件讀取的字符串沒有得到解析到本地日期
這是e.printStackTrace();
獲得的輸出:從文件中讀取
'Loans.txt'.java.time.format.DateTimeParseException: Text '2017/11/01' could not be parsed at index 2
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400)
at ooad1.Ooad1.main(Ooad1.java:119)
Exception occurred trying to read 'Holder.txt'.
您可以更新您的異常打印堆棧跟蹤 – 2017-10-13 14:15:02
問題總是記錄或打印未鏈接到另一個異常捕獲異常的堆棧跟蹤。在你的情況下,你的'catch'塊需要包含'e.printStackTrace();'。一旦你完成了,編輯你的問題,並添加完整的堆棧跟蹤。 – VGR
你是否目測檢查了loans.txt中的數據?也許文件中有一個無效的日期? –