这是我当前的代码:使用用户输入从分隔文本文件中删除特定行。 (JAVA)
import java.util.*;
import java.io.*;
public class Adding_Deleting_Car extends Admin_Menu {
public void delCar() throws IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("inventory.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the VIN of the car you wish to delete/update: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
System.out.println(trimmedLine);
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}
我想从基于用户输入的文件删除文本的某一行。举例来说,这是我的文本文件:
AB234KXAZ;Honda;Accord;1999;10000;3000;G
AB234KL34;Honda;Civic;2009;15000;4000;R
CD555SA72;Toyota;Camry;2010;11000;7000;S
FF2HHKL94;BMW;535i;2011;12000;9000;W
XX55JKA31;Ford;F150;2015;50000;5000;B
我想用户输入自己选择的字符串,这将是f第一栏(例如: XX55JKA31),然后从文件中删除该行文本。我在网上找到了一些代码,但是我一直无法成功使用它。
我目前的代码似乎只是重写临时文本文件中的所有内容,但不会将其删除。
“我目前的代码似乎只是重写临时文本文件中的所有内容,但不会将其删除。”那么这行是什么,然后'tempFile.renameTo(inputFile)'? –
@Patrick Parker它返回false,但我不太确定我应该期待什么,因为我已经在其他地方获得了代码。临时文件只是重新创建我的原始文件,而不删除我想要的行。 –
可能重复的[Reliable File.renameTo()替代Windows?](http://stackoverflow.com/questions/1000183/reliable-file-renameto-alternative-on-windows) –