【发布时间】:2020-08-19 15:16:28
【问题描述】:
我有一个文本文件,inventory.txt,带有
cats, 10, 15
dogs, 10, 15
我想运行一个代码,我可以输入cats 作为replacee 和turtles, 5, 5 作为replacer,给我,
turtles, 5, 5
dogs, 10, 15
但是,当我这样做时,除了我的replacer 之外,第一个逗号之后的所有内容都将保留。我可以将cats 替换为仅turtles 而没有5, 5,给我
turtles, 10, 15
dogs, 10, 15
但是当我尝试在第一个逗号保留后添加5, 5 时,输出如下。
代码
public void modifyItems() throws IOException {
File file = new File("src/inventory.txt");
String line = "";
String oldLine = "";
String replacee;
String replacer;
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
oldLine += line + System.lineSeparator();
}
System.out.println(oldLine);
reader.close();
System.out.println("enter the item you want to edit");
replacee = scan.next();
scan.nextLine();
System.out.println("enter the updated information");
replacer = scan.nextLine();
String newLine = oldLine.replaceAll(replacee, replacer);
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(newLine);
writer.flush();
writer.close();
}
输出
cats, 10, 15
dogs, 10, 15
enter the item you want to edit
cats
enter the updated information
turtles, 5, 5
文本文件输出
turtles, 5, 5, 10, 15
dogs, 10, 15
【问题讨论】: