0
我在獲取該函數時遇到了一些麻煩,所以在這裏提供了上下文的升技。所有這一切,都是一個從3個不同文本文件中刪除一行的按鈕。它通過從主GUI中的textFields中抓取字符串來確定要刪除的字符串,然後搜索相關文件以查找字符串。一旦找到字符串,它們將被寫入臨時文件並刷新。試圖從文本文件中刪除特定的字符串
此代碼實際上工作,但只對第一個文件。我在這段代碼中遇到的唯一問題是最後一次重命名不會出於某種原因而工作?我需要將文件重命名爲原件,以便我的其他軟件可以正常運行。
請任何人都可以幫忙嗎? :)
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// TODO
String name = reminderNameField.getText();
String date = reminderDate.getText();
String details = reminderDetailsField.getText();
File fileName = new File("reminderNames.txt");
File fileDate = new File("reminderDate.txt");
File fileDetails = new File("reminderDetails.txt");
try {
File tempFileN = new File(fileName.getAbsoluteFile() + ".tmp");
File tempFileD = new File(fileDate.getAbsoluteFile() + ".tmp");
File tempFileC = new File(fileDetails.getAbsoluteFile() + ".tmp");
BufferedReader brName = new BufferedReader(new FileReader("reminderNames.txt"));
BufferedReader brDate = new BufferedReader(new FileReader("reminderDate.txt"));
BufferedReader brDetails = new BufferedReader(new FileReader("reminderDetails.txt"));
PrintWriter pwName = new PrintWriter(new FileWriter(tempFileN));
PrintWriter pwDate = new PrintWriter(new FileWriter(tempFileD));
PrintWriter pwDetails = new PrintWriter(new FileWriter(tempFileC));
String lineN = null;
String lineD = null;
String lineC = null;
while ((lineN = brName.readLine()) !=null && (lineD = brDate.readLine()) !=null && (lineC = brDetails.readLine()) !=null) {
if(!lineN.trim().equals(name) && !lineD.trim().equals(date) && !lineC.trim().equals(details)) {
pwName.println(lineN);
pwName.flush();
pwDate.println(lineD);
pwDate.flush();
pwDetails.println(lineC);
pwDetails.flush();
}
}
pwName.close();
pwDate.close();
pwDetails.close();
brName.close();
brDate.close();
brDetails.close();
fileName.delete();
fileDate.delete();
fileDetails.delete();
if(!tempFileN.renameTo(fileName)) {
System.out.println("Cannot rename file");
}
if(!tempFileD.renameTo(fileDate)) {
System.out.println("Cannot rename file date");
}
if(!tempFileC.renameTo(fileDetails)) {
System.out.println("Cannot rename file details");
}
* UPDATE * 寫這個方法中做的工作,但由於某種原因,它僅適用於一個文件?誰能告訴我爲什麼?
public void removeReminder(File a, String search) throws IOException {
File tempFile = new File(a.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(a));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
while ((line = br.readLine()) != null) {
if (!line.trim().equals(search)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
a.delete();
tempFile.renameTo(a);
}
我很困惑。爲什麼你沒有一個函數可以一次處理一個文件,而只是遍歷這三個文件? –
我開始認爲這會很容易,但一直試圖讓它工作的麻煩負荷?你會如何推薦這樣做? –
編寫一個文件的方法。確保首先工作。一旦這樣做,很可能(a)你的問題會神奇地消失,或者(b)問題會神奇地變得明顯。 –