[英]“\n” not adding new line when saving the string to text using BufferWriter to text file
[英]“\n” not adding new line when saving the string to text using PrintWriter
我想使用out.print
將字符串打印到文本,但字符串中的\\n
不起作用。
這是代碼:
import java.io.PrintWriter;
public class LetterRevisited{
public static void main(String[] args)throws Exception
{
PrintWriter out = new PrintWriter("Test.txt");
out.println("This is the first line\n" +
"This is the second line" );
out.close();
}
}
但是在保存的文件中沒有創建新行,所有行都是相繼的。 知道如何解決這個問題嗎? (旁邊將out.println
添加到所有行。)
編輯:我使用Windows命令提示符編譯並運行代碼並使用記事本打開文件。
不同的平台使用不同的行分隔符。
\\r\\n
\\n
\\n
,但過去常常使用\\r
。 (您可以在此處查看更多信息和變體)
您可以使用獲取“本地”行分隔符
System.getProperty("line.separator")
例如
out.println("Hello" + System.getProperty("line.separator") + "World");
但是,在字符串格式化程序中使用%n
更容易:
out.printf("Hello%nWorld%n");
如果您要定位特定平台,則可以使用文字。
如果您使用的是Java 7,則可以使用System.lineSeparator()..看看這是否有幫助。 對於舊版本的Java,您可以使用 - System.getProperty(“line.separator”)
示例:System.out.println(System.lineSeparator()+“這是第二行”);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.