[英]Remove specific line in text file
我有一个.txt 文件inventory.txt
。 它包含
banana, 1, 15
dog, 1, 15
cats, 20, 30
我想创建一种方法,通过输入cats
或cats, 20, 30
来删除这些行之一,比方说cats
行
我的代码提示用户输入removedItem
,读取inventory.txt
,修剪每一行,并检查trimmedLine
是否等于removedItem
,然后continue
并写入deleteditems.txt
读取的每一line
,不包括trimmedLine
。 然后我关闭writer
和reader
,删除原来的inventory.txt
,并将deleteditems.txt
重命名为inventory.txt
。 但是,它什么也没做,编译后该行仍然存在。
代码:
public void removeItems() throws IOException {
String line;
File inventory = new File("src/inventory.txt");
File temp = new File("src/deleteditems.txt");
BufferedReader reader = new BufferedReader(new FileReader("src/inventory.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("src/deleteditems.txt"));
displayInventory();
temp.createNewFile();
System.out.println("what item do you want to remove");
String removedLine = scan.next();
while((line = reader.readLine()) != null) {
String trimmedLine = line.trim();
if(trimmedLine.equals(removedLine)) {
trimmedLine = "";
}
writer.write(line + System.getProperty("line.separator"));
}
reader.close();
writer.close();
inventory.delete();
temp.renameTo(inventory);
}
Output:
banana, 1, 15
dog, 1, 15
cats, 20, 30
what item do you want to remove
cats, 20, 30
编译后的文本文件:
banana, 1, 15
dog, 1, 15
cats, 20, 30
你在做什么有两个问题:
您可以这样修复它:
while((line = reader.readLine()) != null) {
String trimmedLine = line.trim();
if(!trimmedLine.startsWith(removedLine)) {
writer.write(line +
System.getProperty("line.separator"));
}
}
如果它不以输入开头,这将只写该行。
作为旁注,您应该考虑使用“尝试使用资源”语句来打开您的阅读器/编写器,以确保即使在发生异常时也能正确清理。
您正在尝试检查是否与 .equals() 完全匹配
尝试使用.contains(CharSequence) 或.startsWith()
String newInventory = "";
while((line = reader.readLine()) != null) {
String trimmedLine = line.trim();
if(!trimmedLine.contains(removedLine)) {
writer.write(line + System.getProperty("line.separator"));
continue;
}
newInventory += line;
}
FileOutputStream fout = new FileOutputSteam("src/inventory.txt");
fout.write(newInventory.getBytes());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.