您的位置:首页 > 编程语言 > Java开发

Java File and FileSystem 源代码分析

2016-03-05 14:37 851 查看
Java File对象表示的是系统中一个文件或者文件夹,有几个关键字段:

static private FileSystem fs = FileSystem.getFileSystem();
private String path;
public static final char separatorChar = fs.getSeparator();


其中第一个字段是文件系统对象,表示操作系统的文件系统类型。

第二个字段是文件全名或文件夹全名。

第三个字段是分隔符字段。

看一下构造函数:

public File(String pathname) {
if (pathname == null) {
throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
}


主要就是初始化了一个文件名称的参数。

看看其中的一些方法:

public String getName() {
int index = path.lastIndexOf(separatorChar);
if (index < prefixLength) return path.substring(prefixLength);
return path.substring(index + 1);
}
public boolean mkdir() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
return fs.createDirectory(this);
}
public boolean mkdirs() {
if (exists()) {
return false;
}
if (mkdir()) {
return true;
}
File canonFile = null;
try {
canonFile = getCanonicalFile();
} catch (IOException e) {
return false;
}

File parent = canonFile.getParentFile();
return (parent != null && (parent.mkdirs() || parent.exists()) &&
canonFile.mkdir());
}
public boolean renameTo(File dest) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
security.checkWrite(dest.path);
}
return fs.rename(this, dest);
}


等等这些方法,其中主要就是调用了FileSystem文件系统的接口。

第一个方法getName:获取文件名,这个主要就是截取了整个文件名的最后一段。

其他几个创建文件路径,或者是重命名的方法都是调用文件系统的接口。

现在主要来看下文件系统的实现:

文件系统FileSystem 是一个抽象类,在Windows平台上FileSystem有如下实现:

FileSystem

——–Win32FileSystem

————WinNTFileSystem

这个是个继承关系,最终的实现是WinNTFileSystem类。但是很遗憾看到这里,全部的文件操作都是本地方法来做的。

public native boolean createFileExclusively(String path)
throws IOException;
protected native boolean delete0(File f);
public native String[] list(File f);
public native boolean createDirectory(File f);
protected native boolean rename0(File f1, File f2);
public native boolean setLastModifiedTime(File f, long time);
public native boolean setReadOnly(File f);
protected native String getDriveDirectory(int drive);
private static native void initIDs();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 源代码