[英]need to delete a line of text from a file if it contains specific data in Java
我需要能夠根據行中的特定文本(不是整行)刪除一行。
到目前為止這是我所擁有的,但它正在刪除整個文件!! 我可能錯過了半結腸或傻事......有人可以幫忙嗎?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class DeleteStudent
{
public static void removeStudentData()
{
File inputFile = new File("StudentsII.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(inputFile));
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
CharSequence sID = null;
String lineToRemove = (String) sID;
String currentLine;
Scanner UI = new Scanner(System.in);
boolean found = false;
System.out.println("\n***DELETE STUDENT RECORD***\n");
System.out.println("Enter a student ID: ");
sID=UI.next();
try {
while((currentLine = reader.readLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.contains(sID))
continue;
try {
writer.write(currentLine);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean successful = tempFile.renameTo(inputFile);
Menu.displayMenu();
}
}
txt文件包含以下信息...
Martha Stewart 123 Freshman
Cindi Lauper 234 Senior
Tina Turner 345 Freshman
完成編寫后,您需要關閉流和文件:
writer.close();
tempFile.close();
//etc.
使用調試器(或只是println)來查看代碼的哪些位被執行。 例如,打印sID
和trimmedLine
- 它們是你所期望的嗎?
快速瀏覽一下,我看不到任何實際的錯誤,但有一些樣式的東西(通常可以幫助使代碼更具可讀性,從而更容易找到錯誤)
稱為UI
變量有點令人困惑 - 看起來像一個類名或某物(由於主要資本) - 它是100%的合法代碼,但你不會看到太多的程序員使用這種局部變量的命名約定。
if (condition) continue;
有點奇怪 - 我可以看到它的工作原理,但寫起來會更明顯一點
if (!condition) { /* write the line */ }
簡單來看,我發現下面的代碼可疑。 tempFile.renameTo(INPUTFILE);
原因是臨時文件想要重命名為輸入文件,而該文件尚未正確關閉。 根據我的意見,這應該會導致文件IO錯誤。
也許明天,我將使用Eclipse調試器來確定問題。 但你應該這樣做。 如果你獎勵我投票給你最好的答案,那將激勵我這樣做:)
問題你說的哪個文件被刪除了? 我的猜測是臨時文件嗎?
祝好運,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.