【问题标题】:How do I replace a word in my text file using Scanner?如何使用扫描仪替换文本文件中的单词?
【发布时间】: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来读取文件?您打算如何编写文件? PrintWriterFileWriter 附近?如果是这样,为什么不在FileReader 周围使用BufferedReader 阅读? --- 仅供参考: 如果您正在做的只是阅读整行,BufferedReaderScanner很多 倍,这 真的很slooowwwwww.
  • 我想读取文件的所有行,并用另一个用户输入替换文本文件中的用户输入实例。有人告诉我使用Scanner 将是扫描线条并替换单词的最佳方式。我不确定如何使用Scanner 替换单词。我是 Java 新手,所以我不知道要使用哪些其他类。
  • 您不能使用Scanner替换单词Scanner 用于阅读(又名扫描)输入。您可能还不太了解正则表达式,所以 indexOf()substring() 可能是您应该用来替换字符串中的文本的方法。

标签: java replace java.util.scanner words


【解决方案1】:

你不能使用Scanner 类来做到这一点。因为Scanner 类用于只读。您可以将以下单词替换为:

Path path = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;

String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("foo", "bar");
Files.write(path, content.getBytes(charset));

或者您也可以查看BufferedWriterFileWriter。您可以通过工作示例here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多