0

我有一个小问题,\n我的文件中的 ' 在我的输出中不起作用我尝试了两种方法:

请注意:

*此处文件中的文本是一个非常简化的示例。这就是为什么我不只是output.append("\n\n");在第二种方法中使用。此外,\n文件中的 s 并不总是位于行的末尾,即文件中的一行 n 可能是Stipulation 1.1\nUnder this Stipulation...etc。*

文件中的\n's 需要工作。两者都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


方法二:

 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
4

3 回答 3

1

What do you mean with "it is not working"? In what way are they not working? Do you expect to see a line break? I am not sure if you actually have the characters '\n' at the end of each line, or the LineFeed Character (0x0A). The reason your '\n' would work in the Javas source is, that this is a way to escape the linefeed character. Tell us a little about your input file, how is it generated?

Second thing I notice is, that you print the text to the console in the second Method. I am not certain, that the JOptionPane will even display line breaks this way. I think it uses a JLabel, see Java: Linebreaks in JLabels? for that. The console does interpret \n as a linebreak.

于 2013-10-04T18:57:49.743 回答
1

字符序列\n只是不可打印字符的人类可读表示。

从文件中读取它时,您会得到两个字符“\”和“n”,而不是换行符。

因此,您需要将文件中的占位符替换为“真正的”换行符。

使用我前面提到的方法:s = s.replaceAll( "\\\\n", System.lineSeparator() );是一种方法,我相信还有其他方法。

也许在readAllLines您可以添加上面的代码行之前进行替换,或者您将这一行粘贴到rules数组中。

编辑:

这不能按您期望的方式工作的原因是因为您正在从文件中读取它如果它被硬编码到你的类中,编译器会看到 '\n' 序列并说“哦,男孩!行分隔符!我将用 (char)0x0A 替换它”。

于 2013-10-04T19:51:45.883 回答
0

最终答案如下所示:

private static void setGameRules(File f) throws FileNotFoundException, IOException {
        rules = Files.readAllLines(f.toPath(), Charset.defaultCharset());
        for(int i =0;i!=rules.size();i++){
            rules.set(i, rules.get(i).replaceAll( "\\\\n","\n"));
        }
    }

正如@Ray所说\n,文件中的只是被读取为字符\n不是行分隔符\n ,我刚刚添加了一个for-loop来遍历列表并使用以下方法替换它们:

rules.set(i, rules.get(i).replaceAll( "\\\\n","\n")

于 2013-10-04T20:31:21.753 回答