【发布时间】:2017-02-28 07:34:43
【问题描述】:
这是我当前的代码:
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
我希望用户输入他们选择的字符串,这将是列中的第一个字段(例如 XX55JKA31),然后从文件中删除该行文本。我在网上找到了一些代码,但一直无法成功使用。
我当前的代码似乎只是重写了临时文本文件中的所有内容,但没有删除它。
【问题讨论】:
-
"我当前的代码似乎只是重写了临时文本文件中的所有内容,但没有删除它。"那么这条线在做什么
tempFile.renameTo(inputFile)? -
@Patrick Parker 它返回 false,但我不太确定我应该期待什么,因为我在别处得到了代码。临时文件只是重新创建我的原始文件,而不删除我想要的行。