相信技术的力量

Java使用Separator替代符号拼接

为了在Windows,Linux,Mac 等不同平台的适配性,在写代码的时候,文件之间的分隔符,比如D:/develop/Java,尽量不要直接写成死代码"/",而是以代码代替,通过代码来获取系统的分隔符。

'/'符号

  • File.separatorChar
  • File.separator

":"符号

  • File.pathSeparatorChar
  • File.pathSeparator

源码一览无余

/**
 * The FileSystem object representing the platform's local file system.
 */
private static final FileSystem fs = DefaultFileSystem.getFileSystem();

/**
 * The system-dependent default name-separator character.  This field is
 * initialized to contain the first character of the value of the system
 * property <code>file.separator</code>.  On UNIX systems the value of this
 * field is <code>'/'</code>; on Microsoft Windows systems it is <code>'\\'</code>.
 *
 * @see   java.lang.System#getProperty(java.lang.String)
 */
public static final char separatorChar = fs.getSeparator();

/**
 * The system-dependent default name-separator character, represented as a
 * string for convenience.  This string contains a single character, namely
 * <code>{@link #separatorChar}</code>.
 */
public static final String separator = "" + separatorChar;

⬆️