【发布时间】:2017-03-23 22:19:50
【问题描述】:
所以我的代码的目标是使用Scanner 读取文本文件,然后通过文本字段获取用户输入。
然后扫描器将遍历文本文件,试图找到所述用户输入的实例,如果找到该输入,它会替换文本文件中的单词。
然后我写回文件,只改变了一个字。
我的问题是我之前没有使用过 Scanner 并且浏览过文档,我不确定如何正确进行。
到目前为止,这是我的代码,只需单击一个按钮即可激活:
Scanner read = new Scanner("test test.txt");
//Converting user input from editSerialField to a scanner
Scanner scEditSerial = new Scanner(editSerialField.getText());
String scSerial = scEditSerial.nextLine();
//Converting user input from editLocationField to a scanner
Scanner scEditLocation = new Scanner(editLocationField.getText());
String scLocation = scEditSerial.nextLine();
while (read.hasNextLine())
{
//If my text file contains the user input from the text field
if (read.hasNext(scSerial))
{
//Code to replace instance of editSerialField in text file
}
//Code to write back to the file
}
如何使用Scanner 替换文本文件中的单词?我是否应该使用不同的班级来这样做?
我不知道如何继续我的代码,所以任何帮助将不胜感激。
【问题讨论】:
-
那么为什么你要使用
Scanner来读取文件?您打算如何编写文件?PrintWriter在FileWriter附近?如果是这样,为什么不在FileReader周围使用BufferedReader阅读? --- 仅供参考: 如果您正在做的只是阅读整行,BufferedReader比Scanner快 很多 倍,这 真的很slooowwwwww. -
我想读取文件的所有行,并用另一个用户输入替换文本文件中的用户输入实例。有人告诉我使用
Scanner将是扫描线条并替换单词的最佳方式。我不确定如何使用Scanner替换单词。我是 Java 新手,所以我不知道要使用哪些其他类。 -
您不能使用
Scanner替换单词。Scanner用于阅读(又名扫描)输入。您可能还不太了解正则表达式,所以indexOf()和substring()可能是您应该用来替换字符串中的文本的方法。
标签: java replace java.util.scanner words