我有一个小问题,文件中的 \n
在我的输出中不起作用我尝试了两种方法:
请注意:
*此处文件中的文本是一个非常简化的示例。这就是为什么我不只在第二种方法中使用 output.append("\n\n");
。此外,文件中的 \n
并不总是位于行的末尾,即文件中的第 n 行可能是 Stipulation 1.1\nUnder this Stipulation...etc
。 *
文件中的 \n
需要起作用。此外,JOptionPane.showMessageDialog(null,rules);
和 System.out.println(rules);
都提供相同的格式化输出
文件中的文本:
A\n
B\n
C\n
D\n
方法一:
private static void setGameRules(File f) throws FileNotFoundException, IOException
{
rules = Files.readAllLines(f.toPath(), Charset.defaultCharset());
JOptionPane.showMessageDialog(null,rules);
}
输出 1:
A\nB\nC\nD\n
<小时/>
<小时/>
方法2:
private static void setGameRules(File f) throws FileNotFoundException, IOException
{
rules = Files.readAllLines(f.toPath(), Charset.defaultCharset());
StringBuilder output = new StringBuilder();
for (String s : rules)
{
output.append(s);
output.append("\n\n");//these \n work but the ones in my file do not
}
System.out.println(output);
}
输出 2:
A\n
B\n
C\n
D\n
最佳答案
字符序列\n
只是人类可读的不可打印字符的表示。
从文件中读取它时,您会得到两个字符“\”和“n”,而不是换行符。
因此,您需要将文件中的占位符替换为“真正的”换行符。
使用我之前提到的方法:s = s.replaceAll( "\\\\n", System.lineSeparator() );
是一种方法,我确信还有其他方法。
也许在 readAllLines
中,您可以添加上面的代码行来进行替换,或者将其粘贴到 rules
数组中。
编辑:
这不能按您期望的方式工作的原因是因为您正在从文件中读取它。如果它被硬编码到你的类中,编译器会看到 '\n' 序列并说“哦,天哪!行分隔符!我将用 (char)0x0A 替换它”。
关于java -\n 从文件读取到列表然后输出时不起作用。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19188662/