[英]Delete a text file in java
我有一種方法可以刪除包含選定電話號碼的文本文件中的一行。 下面是我的代碼。
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
String selectedphone = Phone.getText();
BufferedReader br = new BufferedReader(new FileReader(file));
// Construct the new file that will later be renamed to the original file
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
// Read from the original file and write to the new
// unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (line.trim().startsWith(selectedphone)) {
continue;
} else {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
file.delete();
if (!file.delete()) {
System.out.println("Could not delete file");
}
//rename tempphonebook.txt file back to phonebook.txt
tempFile.renameTo(file);
if (tempFile.renameTo(file)) {
System.out.println("Update succesful");
} else {
System.out.println("Update failed");
}
} catch (Exception e) {
}
}
我的“phonebook.txt”文件如下
0787465147|John|Doe|924578654v|Colombo|
0715435786|Jane|Doe|6672475845v|Colombo|
0114745755|Foo|Baz|6454753754v|Kandy|
當我單擊帶有“selectedphone”為 0787465147 的“刪除”按鈕時,它將創建一個“tempphonebook.txt”文件,如下所示。
0715435786|Jane|Doe|6672475845v|Colombo|
0114745755|Foo|Baz|6454753754v|Kandy|
然后應該刪除“phonebook.txt”,並將“tempphonebook.txt”重命名為“phonebook.txt”。 問題是我無法刪除“phonebook.txt”文件。 當我點擊“刪除”按鈕時,我得到了這個按摩
Could not delete file
Update failed
有人可以幫我嗎? 提前致謝! :)
您嘗試刪除該文件兩次:
file.delete();
if (!file.delete()) {
刪除第一個file.delete();
您的代碼試圖刪除該文件兩次。 因此,如果文件在第一次嘗試時被刪除,您的第二次調用將無效。 您需要刪除第一個
//file.delete(); //not required
if (!file.delete()) {
使用 try-with-resources。 這適用於大多數情況
是的,刪除用於刪除和重命名文件的額外代碼。
你只需要使用 fileName.delete() 或 fileName.renameTo("name"); 一次。 如果命令成功,它將返回 true。
當你再次使用該命令時,它會嘗試刪除不存在的文件(你已經刪除了這個)。
請參閱此示例刪除文本文件中的行
它處理類似的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.