0

我有一个可以编辑然后保存(更新)到文本文件的 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) {
    }
}
...
}

我的 BookInformation 类:

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;
}
}

谢谢。 在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

4

1 回答 1

3

更改此行

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

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

第二个参数(布尔值)改变它是否应该附加文本文件(添加到它的末尾)或只是重写所有内容。

资料来源:FileWriter 的 Javadoc 构造函数摘要

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.
于 2013-03-24T16:30:41.297 回答