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

标签 java arrays newline replaceall

我已经碰壁了!

在 StackOverflow 上阅读了很多有趣的帖子后,我尝试了很多不同的解决方案,但似乎都不起作用。

假设我有一个 .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 every 循环来打印文本。输出仍然与原始相同。

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

最佳答案

阅读文档,即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 和/或 \n 字符。

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

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

不相关

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

我希望您记得关闭扫描仪,并显示模拟代码,因为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()]);
}

关于java - Scanner next() - 如何替换换行符 [java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41883785/

相关文章:

java - 摘要解析器错误 java.lang.NoSuchMethodException : Employee. <init>()

java - 使用 Java Spring REST 服务并解决 angular.js 问题

javascript - 在 Angular 应用程序中使用复选框输入填充嵌套数组

arrays - 如何统计mongodb中数组元素出现的次数?

arrays - 算法,以便我可以以某种方式索引 2^n 组合,这样我就可以在不使用数组的情况下从 1 的任何索引值回溯到 2^n

java - 如何在 FileOutputStream 的 tex 文件上创建新行

java - Swing 无法将自定义字体与 HTML 标记一起使用

java - 关系运算符在哪些方面不遵守浮点值的 compareTo 契约?

c - 如何在换行符 "\t"之前将字符 "\n"添加到字符串中

Javascript 删除 html 内容中的\n 或\t,pre 标签内除外