Hello i need to delete a specific line from text file after ID search pg ID=2
students.txt
1,Giannis,Oreos,Man
2,Maria,Karra,Woman
3,Maria,Oaka,Woman
And after search and delete to get:
students.txt
1,Giannis,Oreos,Man
3,Maria,Oaka,Woman
But is not working properly
Code so far:
@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);
}
If you want to remove a line by a line number I guess you can do a change to your code like this. You can give the int value of Id to the lineToRemove
variable instead of my hard coded value
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.