File类所属包
package java.io;//所属包
获取一个静态对象FileSystem fs:
private static final FileSystem fs = DefaultFileSystem.getFileSystem();
这个表示获取本地文件系统对象,点进去可以看到:
class DefaultFileSystem {
public static FileSystem getFileSystem() {
return new UnixFileSystem();
}
这个DefaultFileSystem类为默认文件系统的意思,返回了UnixFileSystem()构造函数。盲猜:因为我的电脑是Mac ,所以是返回基于Unix底层的平台。
这个就是FileSystem fs对象的生成过程。
public static final char separatorChar = fs.getSeparator();
定义了一个 separatorChar的分隔字符静态变量名,用的方法是上面文件系统的方法 get.separator得到该系统的文件分字符。
系统依赖默认分割符号,这个变量被初始化包含在系统属性-file.separator中的第一个字符值,在UNIX系统,这个值是‘/’,在windows系统这个值是‘’
public static final String separator = "" + separatorChar;
上面这个是FIle泪下的一个静态final变量,值为就是separatorChar转为String类型。
联想:这也是为什么File.seprator可以作为分隔符在不同系统,因为是个动态变量!
public static final char pathSeparatorChar = fs.getPathSeparator();
这个变量还是通过fs对象得到的PathSeparator,也是一个在不同系统下的变量。然后转换为如下字符形式pathSeparator:
public static final String pathSeparator = "" + pathSeparatorChar;
实际输出
macOS下:
File.separator = / File.separatorChar = / File.pathSeparator = : File.pathSeparatorChar = :
windows下:
File.separator = File.separatorChar = File.pathSeparator = ; File.pathSeparatorChar = ;总结:
File.Separator:在linux和macos的unix平台为/ ,在win系统为\
File.pathSeparator,在linux和macos的unix平台为: win系统为;
To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.
File.Separator 平时用的多,处理路径用的多,比较好理解。 对于File.pathSparator:You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is:
/path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar
So given a list of files you would do something like this:
String listOfFiles = ... String[] filePaths = listOfFiles.split(File.pathSeparator);
上面的目的是将其分割开来。
还有一个比较常用的案例:就是设置windows时候的环境变量Path可以看出
Consider on windows, the PATH environment variable. You use a ;to separate the file paths so on Windows File.pathSeparator would be ;
今天的源码是File类的2种分隔符 File.Separator&File.pathSeparator的源码和具体的一些应用场景的总结。
以上翻译为我个人随意翻译,水平有限,不喜勿喷!
源码来源:File.Java类,149—243行
今天是自学Java的第47天,加油GOGOGO!



