java 在文本文件中写入“\n”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7063567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a "\n" in a text file
提问by DFE
I'm trying to write a string \n in a text file. But the result in the text file is a newline. I know that the \n represents a newline. But in my case, I really need to see the String \n, not the newline. How can I solve this?
我正在尝试在文本文件中写入一个字符串 \n。但是文本文件中的结果是换行符。我知道 \n 代表换行符。但就我而言,我真的需要看到字符串 \n,而不是换行符。我该如何解决这个问题?
回答by Charles Keepax
The \ character escapes the next character, as you say \n will create a newline. If you wish to output an actual \, you need to write:
\ 字符转义下一个字符,正如您所说的 \n 将创建一个换行符。如果你想输出一个实际的\,你需要写:
"\n"
That way the first slash escapes the second slash, generating an actual slash rather than escaping the n.
这样第一个斜线就可以转义第二个斜线,生成一个实际的斜线而不是转义 n。
回答by Nicola Musatti
Use "\\n"
. The first backslash escapes the second one and as a result one is printed to your output.
使用"\\n"
. 第一个反斜杠将第二个反斜杠转义,结果将一个反斜杠打印到您的输出中。
回答by berlindev
you have to escape the backslash, so double it:
你必须逃避反斜杠,所以加倍:
out("\n")
回答by Peter Lawrey
Do you mean
你的意思是
pw.print("\n"); // print \ and n
instead of
代替
pw.print("\n"); // print new line.
回答by borrible
You need to escape the \
. This can be done by entering \\
.
你需要逃离\
. 这可以通过输入来完成\\
。
回答by Sebastian Mach
What you want is to print two characters, namely \
and n
. According to your language's manual, to print \
you must escape it. n
is not among the characters you must escape. Therefore, you write \\
and n
, thus \\n
.
你想要的是打印两个字符,即\
和n
。根据您的语言手册,要打印,\
您必须将其转义。n
不是您必须转义的字符之一。因此,你写\\
和n
,因此\\n
。