2013-03-24 73 views
0

我有一個jtable,可以edite,然後保存(更新)到一個文本文件。 用戶選擇一行(包含書籍記錄)並請求借用該書, 我使用此方法更新,但現在更新時,舊數據不會被刪除。更新文本文件的方法

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

感謝。 enter image description here enter image description here enter image description here

+0

看起來你有Windows 7的在未來更好的截圖,在開始菜單中輸入「截圖工具」並使用它。 – jessechk 2013-03-24 16:28:10

+0

參見[*我如何創建屏幕截圖?*](http://meta.stackexchange.com/questions/99734/how-do-i-create-a-screenshot-to-illustrate-a-post) – trashgod 2013-03-24 16:30:23

回答

3

改變這一行

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

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

第二個參數(布爾)改變是否應該追加文本文件(添加到它的結束)或者只是重寫一切。

來源: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. 
+0

哦, 謝謝..... – Sajad 2013-03-24 16:39:14