我需要能够根据行中的特定文本(不是整行)删除一行。
到目前为止,这就是我所拥有的,但它正在删除整个文件!我可能错过了一个半冒号或一些愚蠢的东西..有人可以帮忙吗?
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