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'.
答案 0 :(得分:1)
从文件读取的字符串未被解析为localdate
LocalDate是一个不可变类,它表示默认格式为yyyy-MM-dd的Date。我们可以使用now()方法获取当前日期。我们还可以提供年,月和日的输入参数来创建LocalDate实例。
使用格式化程序解析java.time.LocalDate
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate ldate = LocalDate.parse("2017/11/01", formatter);
然后,您可以使用LocalDate
作为setter
方法,之后不会有例外。
例如
setIssueDate(ldate);
setReturnDate(ldate);