概述
java.io.file类即文件和目录名的抽象表示形式。Java将电脑中的文件和文件夹封装成了一个File类,我们可以使用File类对文件和文件夹进行操作
File下静态变量
//与系统有关的路径分隔符
//windos下为:分号
//linux下为:冒号
public static final char pathSeparatorChar = fs.getPathSeparator();
public static final String pathSeparator = "" + pathSeparatorChar;
//与系统有关的名称分隔符
//windows下为:反斜杠\
//linux下为:正斜杠/
public static final char separatorChar = fs.getSeparator();
public static final String separator = "" + separatorChar;
注意:
- 路径是不区分大小写的
- 路径中的文件名称分隔符windows使用反斜杠,但由于路径通过字符串的形式表示,而字符串下反斜杠为特殊字符,因此需要再加一个反斜杠作为转义字符,此时两个反斜杠代表一个普通的反斜杠
File的构造方法
File源码
//pathname:字符串的路径名称
//路径可以是文件结尾,也可以是文件夹结尾
//路径可以是相对路径。也可以是绝对路径
//路径可以是存在的,也可以是不存在的
//创建File对象,只是把字符串路径封装为File对象,不考虑路径的真实情况
public File(String pathname) {
if (pathname == null) {
throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
}
//根据parent路径和child路径创建一个新的File实例
public File(String parent, String child) {
if (child == null) {
throw new NullPointerException();
}
if (parent != null) {
if (parent.equals("")) {
this.path = fs.resolve(fs.getDefaultParent(),
fs.normalize(child));
} else {
this.path = fs.resolve(fs.normalize(parent),
fs.normalize(child));
}
} else {
this.path =