楔子
java操作文件是涉及到换行符。
apache.commons.io.IOUtils
中会自动获取换行符。虽然不清楚 IO jar是怎么实现的。
IOUtils中代码
public static final String LINE_SEPARATOR_UNIX = "\n";
/**
* The Windows line separator string.
*/
public static final String LINE_SEPARATOR_WINDOWS = "\r\n";
/**
* The system line separator string.
*/
public static final String LINE_SEPARATOR;
static {
// avoid security issues
StringBuilderWriter buf = new StringBuilderWriter(4);
PrintWriter out = new PrintWriter(buf);
out.println();
LINE_SEPARATOR = buf.toString();
out.close();
}
测试
public static void main(String[] args) {
////////////////////////////////////////////
char DIR_SEPARATOR = File.separatorChar;
System.out.println("文件系统分隔符"+DIR_SEPARATOR);
/////////////////////////////////////////////
StringBuilderWriter buf = new StringBuilderWriter(4);
PrintWriter out = new PrintWriter(buf);
out.println();
String LINE_SEPARATOR = buf.toString();
if (IOUtils.LINE_SEPARATOR_UNIX.equals(LINE_SEPARATOR)) {
System.out.println("Linux 换行符");
} else if (IOUtils.LINE_SEPARATOR_WINDOWS.equals(LINE_SEPARATOR)) {
System.out.println("window 换行符");
}
out.close();
}