Scanner next() - 如何替换换行符 [java]

Scanner next() - how to replace line breaks [java]

我撞墙了!

在 Whosebug 上阅读了很多有趣的帖子后,我尝试了很多不同的解决方案,但似乎没有任何效果。

假设我有一个 .txt 文件,我想在其中用 "XXX" 替换换行符。我使用计数方法来计算文档中的行数。

Scanner reader = new Scanner("document.txt);

String [] textToArray = new String[count];

for(int i = 0; textToArray.length; i++){
String text = reader.nextLine();

text = text.replaceAll("\n", "XXX");
textToArray[i] = text;

}

然后我使用 for each 循环来打印文本。输出还是和原来一样。

我也试过“\n”、“\r”、“\r”甚至“\r\n”。

String text = reader.nextLine();

text = text.replaceAll("\n", "XXX");

读一行时,不会有换行触发全部替换。您将在文本中看到您当时阅读的任何一行。

尝试构建一个字符串或将完整文本放入一个字符串中,然后替换新行。

阅读文档,即 nextLine():

的 javadoc

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

因此,您正在阅读每一行的文本,但您不会看到 \r and/or \n 个字符。

由于您正在将每一行读入数组,因此您应该将 XXX 附加到每个值:

for (int i = 0; textToArray.length; i++) {
    String text = reader.nextLine();
    textToArray[i] = text + "XXX";
}

无关

我还建议您读入 List,而不是数组。之后您可以随时转换为数组。

我希望你记得关闭 Scanner,并且你展示了模拟代码,因为 new Scanner("document.txt") 将扫描文本 document.txt,而不是文件的内容名字.

String[] textToArray;
try (Scanner reader = new Scanner(new File("document.txt"))) {
    List<String> textList = new ArrayList<>();
    for (String text; (text = reader.nextLine()) != null; ) {
        textList.add(text + "XXX");
    }
    textToArray = textList.toArray(new String[textList.size()]);
}

如果我理解你的问题,你想在给定的例子中用 XXX 替换“\n”?像这样将整个文件读成一个字符串会更容易:

String file = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);

然后您可以使用内置函数,例如:

String replace(char oldChar, char newChar);

这将 return 一个包含您的文件的新字符串,所有空格都替换为 XXX。或者你想在那里使用的任何字符。