java中实现换行有几种方法?

Python028

java中实现换行有几种方法?,第1张

java中实现换行有以下几种方法:\x0d\x0a1.使用java中的转义符"\r\n": \x0d\x0aString str="aaa" \x0d\x0astr+="\r\n" \x0d\x0a这样在str后面就有换行了. \x0d\x0a注意:\r,\n的顺序是不能够对换的,否则不能实现换行的效果. \x0d\x0a2.BufferedWriter的newline()方法: \x0d\x0aFileOutputStream fos=new FileOutputStream("c\\11.txt") \x0d\x0aBufferedWriter bw=new BufferedWriter(fos) \x0d\x0abw.write("你好") \x0d\x0abw.newline() \x0d\x0abw.write("java") \x0d\x0aw.newline() \x0d\x0a3.使用System.getProperty()方法: \x0d\x0aString str = "aaa"+System.getProperty("line.separator") \x0d\x0a附:针对常用的系统,可以使用如下的转义符实现换行: \x0d\x0awindows下的文本文件换行符:\r\n \x0d\x0alinux/unix下的文本文件换行符:\r \x0d\x0aMac下的文本文件换行符:\n

Java中可以使用 System.getProperty("line.separator") 来识别回车换行符。例如:

String lineSeparator = System.getProperty("line.separator")

String text = "This is a line of text" + lineSeparator + "This is another line of text"

上面的代码中,lineSeparator 变量包含了当前系统的回车换行符,然后我们可以在拼接字符串时使用它来指定换行符。

可以用三种方法实现换行操作,分别用System.out.println()语句进行输出,用换行字符'\r\n',以及用BufferedWriter的newline()方法,具体使用哪一种可以根据具体的场景进行选择。