从文件中读取时,Java无法识别\ n

发布于 2025-01-25 03:56:03 字数 459 浏览 1 评论 0原文

如果我直接按照

System.out.println("a\nb");

预期进行打印,并且字符之间有新的线条, 但是,如果我使用显示的文本从文本文件中读取相同的行,

public static void main(String[] args) throws IOException {
    List<String> lines;
    lines = Files.readAllLines(Paths.get("filename.txt"));
    String[] array = lines.toArray(new String[0]);
    System.out.println(array[0]);

将完全按照“ a \ nb”中的文本书写,而没有新的字符之间的新行。 Tostring和其他方法无济于事。

我应该如何更新代码?

If I print directly as

System.out.println("a\nb");

the result will be as expected, with a new line between characters,
but if I read the same line from a text file using

public static void main(String[] args) throws IOException {
    List<String> lines;
    lines = Files.readAllLines(Paths.get("filename.txt"));
    String[] array = lines.toArray(new String[0]);
    System.out.println(array[0]);

the text displayed will be exactly as written in a file "a\nb" without a new line between the characters. toString and other methods do not help.

How should I update the code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

软糖 2025-02-01 03:56:03

在同事和评论者的帮助下,得到了解释和答案(虽然不是最优雅的方法)。
代码中的“ \ n”被解释为一个新的行字符,但是当从文件中读取时,它将变成两个字符:“ \”和“ n”,并且不再被正确识别。消除问题的最短方法是将这些字符替换为程序代码中的新行,并添加“替换(“ \ n”,“ \ n”)”。因此,代码变为如下:

public static void main(String[] args) throws IOException {
    List<String> lines;
    lines = Files.readAllLines(Paths.get("filename.txt"));
    String[] array = lines.toArray(new String[0]);
    System.out.println(array[0].replace("\\n", "\n"));

With the help of the colleagues and commenters got an explanation and an answer (not the most elegant approach though).
"\n" in the code is interpreted as a new line character, but when read from a file it becomes a set of two characters: "\" and "n" and is no longer properly recognized. The shortest way to eliminate the problem would be to replace these characters with the new line in the code of the program, adding "replace("\n", "\n")". So, the code becomes as follows:

public static void main(String[] args) throws IOException {
    List<String> lines;
    lines = Files.readAllLines(Paths.get("filename.txt"));
    String[] array = lines.toArray(new String[0]);
    System.out.println(array[0].replace("\\n", "\n"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文