我想使用来将字符串打印到文本,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");
如果您要针对特定平台,则可以只使用文字。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句