[英]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.