我编写的代码可以使用扫描仪类在文本文件中搜索某些特定文本(例如单词),但我还想在相同的旧文本位置中替换(旧文本到新文本)。 我在互联网上发现我必须使用像(replaceAll(old, new);)这样的replaceAll方法 但它不适用于扫描仪类。
这是我的代码,它只是搜索(如果存在)在新行中写入新文本,而不更改旧文本。
我需要将方法(获取数据)从扫描仪更改为 FileReader 吗?
File file = new File("C:\\Users....file.txt");
Scanner input = new Scanner(System.in);
System.out.println("Enter the content you want to change:");
String Uinput = input.nextLine();
System.out.println("You want to change it to:");
String Uinput2 = input.nextLine();
Scanner scanner = new Scanner(file).useDelimiter(",");
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
while (scanner.hasNextLine()) {
String lineFromFile = scanner.next();
if (lineFromFile.contains(Uinput)) {
lineFromFile = Uinput2;
writer.write(lineFromFile);
writer.close();
System.out.println("changed " + Uinput + " tO " + Uinput2);
break;
}
else if (!lineFromFile.contains(Uinput)){
System.out.println("Don't found " + Uinput);
break;
}
}
最佳答案
您无法从文件中读取内容,然后写入同一文件。您需要 2 个不同的文件。
while (read line from input file) {
if (NOT matches your search pattern)
write line to output file.
else { // matches
write start of line to your search pattern.
write your replace string
write from end of search pattern to end of line.
}
}
除非您的替换字符串与搜索字符串大小相同,否则您必须使用 2 个文件。考虑该文件:
Blah
Blah
Blah
现在将字母“a”替换为“敏捷的棕色狐狸”。如果替换第一行,则会覆盖文件的其余部分。现在您无法读取第二行,所以是的,您必须使用 2 个文件。
关于java - 使用扫描仪类更改文本文件中的特定文本(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47840003/