从文件中读取时,Java无法识别\ n
如果我直接按照
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在同事和评论者的帮助下,得到了解释和答案(虽然不是最优雅的方法)。
代码中的“ \ n”被解释为一个新的行字符,但是当从文件中读取时,它将变成两个字符:“ \”和“ n”,并且不再被正确识别。消除问题的最短方法是将这些字符替换为程序代码中的新行,并添加“替换(“ \ 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: