大家好,我是三叔,这期给大家说一下跨平台换行符的问题,很多读者刚开始接触导入导出文件,使用换行符可能都会出现此类问题。
Java 具有跨平台的特性,如果在Java中把它们固定了,写成绝对路径,Java跨平台的特性就没有了。例如:\r\n 换行符。
在 Windows 下的路径分隔符和 Linux 下的路径分隔符是不一样的,windows 下的文件路径是:\User\xxxx.txt
而 Linux 路径下是:/User/xxxx.txt
StringBuffer sb = new StringBuffer();
sb.append("========测试========").append("\r\n");
// === 文件流之类的处理
Java 提供了跨平台的换行符,根据系统进行自动的匹配:System.lineSeparator()
StringBuffer sb = new StringBuffer();
sb.append("========测试========").append(System.lineSeparator());
// === 文件流之类的处理
System.lineSeparator()源码如下:可以看出,返回系统相关的行分隔符字符串。它总是返回相同的值——系统属性line.separator的初始值。
在 UNIX 系统上,它返回 “\n”; 在 Microsoft Windows 系统上,它返回 “\r\n”。
/**
* Returns the system-dependent line separator string. It always
* returns the same value - the initial value of the {@linkplain
* #getProperty(String) system property} {@code line.separator}.
*
* On UNIX systems, it returns {@code "\n"}; on Microsoft
* Windows systems it returns {@code "\r\n"}.
*
* @return the system-dependent line separator string
* @since 1.7
*/
public static String lineSeparator() {
return lineSeparator;
}