您好,我需要在 ID 搜索后从文本文件中删除特定行。 ID=2
students.txt
1,Giannis,Oreos,Man
2,Maria,Karra,Woman
3,Maria,Oaka,Woman
搜索删除后得到:
students.txt
1,Giannis,Oreos,Man
3,Maria,Oaka,Woman
但无法正常工作
到目前为止的代码:
@FXML
TextField ID2;
@FXML
public void UseDelete() throws IOException {
File inputFile = new File("src/inware/students.txt");
File tempFile = new File("src/inware/studentsTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = ID2.getText();
String currentLine;
while ((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if (trimmedLine.equals(lineToRemove)) {
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
}
最佳答案
如果您想按行号删除一行,我想您可以像这样更改代码。您可以将 Id 的 int 值赋予 lineToRemove
变量,而不是我的硬编码值
import java.io.*;
public class A {
public static void main(String[] args) throws IOException {
new A().useDelete();
}
public void useDelete() throws IOException {
File inputFile = new File("src/inware/students.txt");
File tempFile = new File("src/inware/studentsTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
int lineToRemove = 2;
String currentLine;
int count = 0;
while ((currentLine = reader.readLine()) != null) {
count++;
if (count == lineToRemove) {
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
}
关于java - 从txt文件中删除特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53248156/