gpt4 book ai didi

java - 更新文本文件方法

转载 作者:行者123 更新时间:2023-12-01 23:56:05 25 4
gpt4 key购买 nike

我有一个可以编辑的 jtable,然后保存(更新)到文本文件。用户选择一行(包含图书记录)并请求借阅该书,我就是用这个方法更新的,但是现在更新的时候,旧的数据没有被删除。

user_AllBooks uAllBooks = new user_AllBooks();
@Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == borrowButton) {
borrowInitialize(bTable.getSelectedRow());
}

public void borrowInitialize(int row) {
if (uAllBooks.getValueAt(row, 3).equals("Yes")) {
JOptionPane.showMessageDialog(null, "This Book Was Borrowed");
} else {
uAllBooks.setValueAt("Yes", row, 3);
uAllBooks.fireTableRowsUpdated(row, row);
uAllBooks.updateFiles(uAllBooks.bData);
}
}
...
}

public class user_AllBooks extends AbstractTableModel {
...

public void updateFiles(ArrayList<BookInformation> data) {
PrintWriter Bpw = null;
try {
Bpw = new PrintWriter(new FileWriter("AllBookRecords.txt" , true));
for (BookInformation bookinfo : data) {
String line = bookinfo.getBookID()
+ " " + bookinfo.getBookName()
+ " " + bookinfo.getBookDate()
+ " " + bookinfo.getBorrowStatus();
Bpw.println(line);
}

Bpw.close();
} catch (FileNotFoundException e1) {
} catch (IOException ioe) {
}
}
...
}

我的图书信息类:

public class BookInformation {

private String BookName;
private String BookDate;
private String BookID;
private String BorrowStatus;

public String getBookName() {
return BookName;
}

public void setBookName(String book_name) {
this.BookName = book_name;
}

public String getBookDate() {
return BookDate;
}

public void setBookDate(String book_date) {
this.BookDate = book_date;
}

public String getBookID() {
return BookID;
}

public void setBookID(String Book_id) {
this.BookID = Book_id;
}

@Override
public String toString() {
return BookID + " " + BookName + " "
+ BookDate + " " + BorrowStatus + "\n";
}

public String getBorrowStatus() {
return BorrowStatus;
}

public void setBorrowStatus(String borrowStat) {
BorrowStatus = borrowStat;
}
}

谢谢。 enter image description here enter image description here enter image description here

最佳答案

更改此行

Bpw = new PrintWriter(new FileWriter("AllBookRecords.txt" , true));

Bpw = new PrintWriter(new FileWriter("AllBookRecords.txt" , false));

第二个参数( boolean 值)更改是否应附加文本文件(添加到其末尾)或只是重写所有内容。

来源:Javadoc constructor summary for FileWriter :

FileWriter(String fileName, boolean append) 
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.

关于java - 更新文本文件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15600839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com