我想使用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
。(你可以看到更多的信息和变种here)
您可以使用获取“本地”行分隔符
System.getProperty("line.separator")
EG
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()+“这是第二行”);