// 静态成员
public static final String pathSeparator // 路径分割符":"
public static final char pathSeparatorChar // 路径分割符':'
public static final String separator // 分隔符"/"
public static final char separatorChar // 分隔符'/'
// 构造函数
File(File dir, String name)
File(String path)
File(String dirPath, String name)
File(URI uri)
// 成员函数
boolean canExecute() // 测试应用程序是否可以执行此抽象路径名表示的文件。
boolean canRead() // 测试应用程序是否可以读取此抽象路径名表示的文件。
boolean canWrite() // 测试应用程序是否可以修改此抽象路径名表示的文件。
int compareTo(File pathname) // 按字母顺序比较两个抽象路径名。
boolean createNewFile() // 当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。
static File createTempFile(String prefix, String suffix) // 在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。
static File createTempFile(String prefix, String suffix, File directory) // 在指定目录中创建一个新的空文件,使用给定的前缀和后缀字符串生成其名称。
boolean delete() // 删除此抽象路径名表示的文件或目录。
void deleteOnExit() // 在虚拟机终止时,请求删除此抽象路径名表示的文件或目录。
boolean equals(Object obj) // 测试此抽象路径名与给定对象是否相等。
boolean exists() // 测试此抽象路径名表示的文件或目录是否存在。
File getAbsoluteFile() // 返回此抽象路径名的绝对路径名形式。
String getAbsolutePath() // 返回此抽象路径名的绝对路径名字符串。
File getCanonicalFile() // 返回此抽象路径名的规范形式。
String getCanonicalPath() // 返回此抽象路径名的规范路径名字符串。
long getFreeSpace() // 返回此抽象路径名指定的分区中未分配的字节数。
String getName() // 返回由此抽象路径名表示的文件或目录的名称。
String getParent() // 返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回 null。
File getParentFile() // 返回此抽象路径名父目录的抽象路径名;如果此路径名没有指定父目录,则返回 null。
String getPath() // 将此抽象路径名转换为一个路径名字符串。
long getTotalSpace() // 返回此抽象路径名指定的分区大小。
long getUsableSpace() // 返回此抽象路径名指定的分区上可用于此虚拟机的字节数。
int hashCode() // 计算此抽象路径名的哈希码。
boolean isAbsolute() // 测试此抽象路径名是否为绝对路径名。
boolean isDirectory() // 测试此抽象路径名表示的文件是否是一个目录。
boolean isFile() // 测试此抽象路径名表示的文件是否是一个标准文件。
boolean isHidden() // 测试此抽象路径名指定的文件是否是一个隐藏文件。
long lastModified() // 返回此抽象路径名表示的文件最后一次被修改的时间。
long length() // 返回由此抽象路径名表示的文件的长度。
String[] list() // 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。
String[] list(FilenameFilter filter) // 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中满足指定过滤器的文件和目录。
File[] listFiles() // 返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。
File[] listFiles(FileFilter filter) // 返回抽象路径名数组,这些路径名表示此抽象路径名表示的目录中满足指定过滤器的文件和目录。
File[] listFiles(FilenameFilter filter) // 返回抽象路径名数组,这些路径名表示此抽象路径名表示的目录中满足指定过滤器的文件和目录。
static File[] listRoots() // 列出可用的文件系统根。
boolean mkdir() // 创建此抽象路径名指定的目录。
boolean mkdirs() // 创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。
boolean renameTo(File dest) // 重新命名此抽象路径名表示的文件。
boolean setExecutable(boolean executable) // 设置此抽象路径名所有者执行权限的一个便捷方法。
boolean setExecutable(boolean executable, boolean ownerOnly) // 设置此抽象路径名的所有者或所有用户的执行权限。
boolean setLastModified(long time) // 设置此抽象路径名指定的文件或目录的最后一次修改时间。
boolean setReadable(boolean readable) // 设置此抽象路径名所有者读权限的一个便捷方法。
boolean setReadable(boolean readable, boolean ownerOnly) // 设置此抽象路径名的所有者或所有用户的读权限。
boolean setReadOnly() // 标记此抽象路径名指定的文件或目录,从而只能对其进行读操作。
boolean setWritable(boolean writable) // 设置此抽象路径名所有者写权限的一个便捷方法。
boolean setWritable(boolean writable, boolean ownerOnly) // 设置此抽象路径名的所有者或所有用户的写权限。
String toString() // 返回此抽象路径名的路径名字符串。
URI toURI() // 构造一个表示此抽象路径名的 file: URI。
URL toURL() // 已过时。 此方法不会自动转义 URL 中的非法字符。建议新的代码使用以下方式将抽象路径名转换为 URL:首先通过 toURI 方法将其转换为 URI,然后通过 URI.toURL 方法将 URI 装换为 URL。
File常用的方法:
一、创建目录常用的方法
(1)根据相对路径创建目录
File dir = new File("dir");
dir.mkdir();//在当前目录下创建目录
(2)根据绝对路径创建目录
File dir = new File("/home/skywang/dir");
dir.mkdirs();
(3)URI方法
URI uri = new URI("file:/home/skywang/dir");
File dir = new File(uri);
dir.mkdir();
二、新建子目录几种常用方法
(1)在当前子目录下创建一个目录
File sub1 = new File("dir", "sub1");//目录dir必须是存在的
sub1.mkdir();
(2)通过目录创建目录
File sub3 = new File("dir/sub3");//dir不一定存在,当不存在时会创建
sub3.mkdirs();
(3)绝对目录创建目录
File sub4 = new File("/home/skywang/dir/sub4");//当目录不存在时会创建
sub4.mkdirs();
(4)URI方式
URI uri = new URI("file:/home/skywang/dir/sub5");//和(3)一样,目录不存在就创建
File sub5 = new File(uri);
sub5.mkdirs();
三、新建文件的常用方法
(1)在当前子目录下创建文件
try {
File dir = new File("dir"); // 获取目录“dir”对应的File对象
File file1 = new File(dir, "file1.txt");
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
(2)相对目录下创建文件
try {
File file2 = new File("dir", "file2.txt");
file2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
(3)绝对路径创建文件
try {
File file3 = new File("/home/skywang/dir/file3.txt");
file3.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
(4)URI方式创建文件
try {
URI uri = new URI("file:/home/skywang/dir/file4.txt");
File file4 = new File(uri);
file4.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
基于JDK8的File类
源码:
public class File implements Serializable, Comparable { //获得当前系统平台的文件系统 private static final FileSystem fs = DefaultFileSystem.getFileSystem(); //路径名 private final String path; private static enum PathStatus { INVALID, CHECKED }; private transient PathStatus status = null; //判断路径是否有效 final boolean isInvalid() { if (status == null) { status = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED: PathStatus.INVALID; } return status == PathStatus.INVALID; } //文件前缀长度 private final transient int prefixLength; //获得前缀长度 int getPrefixLength() { return prefixLength; }
/** * 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. On UNIX systems the value of this * field is <code>'/'; on Microsoft Windows systems it is <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}. */ // public static final String separator = "" + separatorChar; /** * The system-dependent path-separator character. This field is * initialized to contain the first character of the value of the system * property <code>path.separator. This character is used to * separate filenames in a sequence of files given as a <em>path list</em>. * On UNIX systems, this character is <code>':'; on Microsoft Windows systems it * is <code>';'. * * @see java.lang.System#getProperty(java.lang.String) */ public static final char pathSeparatorChar = fs.getPathSeparator(); /** * The system-dependent path-separator character, represented as a string * for convenience. This string contains a single character, namely * <code>{@link #pathSeparatorChar}. */ public static final String pathSeparator = "" + pathSeparatorChar; /* -- Constructors -- */ /** * Internal constructor for already-normalized pathname strings. */ // private File(String pathname, int prefixLength) { this.path = pathname; this.prefixLength = prefixLength; } /** * Internal constructor for already-normalized pathname strings. * The parameter order is used to disambiguate this method from the * public(File, String) constructor. */ //内部构造函数 private File(String child, File parent) { assert parent.path != null; assert (!parent.path.equals("")); this.path = fs.resolve(parent.path, child); this.prefixLength = parent.prefixLength; } /** * Creates a new <code>File instance by converting the given * pathname string into an abstract pathname. If the given string is * the empty string, then the result is the empty abstract pathname. * * @param pathname A pathname string * @throws NullPointerException * If the <code>pathname argument is <code>null */ //通过路径名构造一个对象 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 = fs.normalize(child); } this.prefixLength = fs.prefixLength(this.path); } public File(File parent, String child) { if (child == null) { throw new NullPointerException(); } if (parent != null) { if (parent.path.equals("")) { this.path = fs.resolve(fs.getDefaultParent(), fs.normalize(child)); } else { this.path = fs.resolve(parent.path, fs.normalize(child)); } } else { this.path = fs.normalize(child); } this.prefixLength = fs.prefixLength(this.path); } //通过URI创建文件对象 public File(URI uri) { // Check our many preconditions if (!uri.isAbsolute()) throw new IllegalArgumentException("URI is not absolute"); if (uri.isOpaque()) throw new IllegalArgumentException("URI is not hierarchical"); String scheme = uri.getScheme(); if ((scheme == null) || !scheme.equalsIgnoreCase("file")) throw new IllegalArgumentException("URI scheme is not \"file\""); if (uri.getAuthority() != null) throw new IllegalArgumentException("URI has an authority component"); if (uri.getFragment() != null) throw new IllegalArgumentException("URI has a fragment component"); if (uri.getQuery() != null) throw new IllegalArgumentException("URI has a query component"); String p = uri.getPath(); if (p.equals("")) throw new IllegalArgumentException("URI path component is empty"); // Okay, now initialize p = fs.fromURIPath(p); if (File.separatorChar != '/') p = p.replace('/', File.separatorChar); this.path = fs.normalize(p); 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 String getParent() { int index = path.lastIndexOf(separatorChar); if (index < prefixLength) { if ((prefixLength > 0) && (path.length() > prefixLength)) return path.substring(0, prefixLength); return null; } return path.substring(0, index); } public File getParentFile() { String p = this.getParent(); if (p == null) return null; return new File(p, this.prefixLength); } //获得路径 public String getPath() { return path; } /* -- Path operations -- */ //是否是绝对路径 public boolean isAbsolute() { return fs.isAbsolute(this); } //返回绝对路径 public String getAbsolutePath() { return fs.resolve(this); } public File getAbsoluteFile() { String absPath = getAbsolutePath(); return new File(absPath, fs.prefixLength(absPath)); } //获得标准的路径 public String getCanonicalPath() throws IOException { if (isInvalid()) { throw new IOException("Invalid file path"); } return fs.canonicalize(fs.resolve(this)); } //获得标准的文件 public File getCanonicalFile() throws IOException { String canonPath = getCanonicalPath(); return new File(canonPath, fs.prefixLength(canonPath)); } private static String slashify(String path, boolean isDirectory) { String p = path; if (File.separatorChar != '/') p = p.replace(File.separatorChar, '/'); if (!p.startsWith("/")) p = "/" + p; if (!p.endsWith("/") && isDirectory) p = p + "/"; return p; } @Deprecated public URL toURL() throws MalformedURLException { if (isInvalid()) { throw new MalformedURLException("Invalid file path"); } return new URL("file", "", slashify(getAbsolutePath(), isDirectory())); } //把绝对文件转换成URI public URI toURI() { try { File f = getAbsoluteFile(); String sp = slashify(f.getPath(), f.isDirectory()); if (sp.startsWith("//")) sp = "//" + sp; return new URI("file", null, sp, null); } catch (URISyntaxException x) { throw new Error(x); // Can't happen } } /* -- Attribute accessors -- */ //文件是否可读 public boolean canRead() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return fs.checkAccess(this, FileSystem.ACCESS_READ); } //可写 public boolean canWrite() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.checkAccess(this, FileSystem.ACCESS_WRITE); } //判断文件或路径是否存在 public boolean exists() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return ((fs.getBooleanAttributes(this) & FileSystem.BA_EXISTS) != 0); } //判断是否是目录 public boolean isDirectory() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY) != 0); } //判断是否是文件 public boolean isFile() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return ((fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0);
}
//判断是否是隐藏
public boolean isHidden() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(path);
}
if (isInvalid()) {
return false;
}
return ((fs.getBooleanAttributes(this) & FileSystem.BA_HIDDEN) != 0);
}
//返回最后修改的时间
public long lastModified() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(path);
}
if (isInvalid()) {
return 0L;
}
return fs.getLastModifiedTime(this);
}
//返回文件的长度
public long length() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(path);
}
if (isInvalid()) {
return 0L;
}
return fs.getLength(this);
}
/* -- File operations -- */
//创建一个空文件
public boolean createNewFile() throws IOException {
SecurityManager security = System.getSecurityManager();
if (security != null) security.checkWrite(path);
if (isInvalid()) {
throw new IOException("Invalid file path");
}
return fs.createFileExclusively(path);
}
//删除文件或目录
public boolean delete() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkDelete(path);
}
if (isInvalid()) {
return false;
}
return fs.delete(this);
}
//删除存在的
public void deleteOnExit() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkDelete(path);
}
if (isInvalid()) {
return;
}
DeleteOnExitHook.add(path);
}
//目录下的所有目录或文件
public String[] list() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(path);
}
if (isInvalid()) {
return null;
}
return fs.list(this);
}
public String[] list(FilenameFilter filter) {
String names[] = list();
if ((names == null) || (filter == null)) {
return names;
}
List<string> v = new ArrayList<>();
for (int i = 0 ; i < names.length ; i++) {
if (filter.accept(this, names[i])) {
v.add(names[i]);
}
}
return v.toArray(new String[v.size()]);
}
public File[] listFiles() {
String[] ss = list();
if (ss == null) return null;
int n = ss.length;
File[] fs = new File[n];
for (int i = 0; i < n; i++) {
fs[i] = new File(ss[i], this);
}
return fs;
}
public File[] listFiles(FilenameFilter filter) {
String ss[] = list();
if (ss == null) return null;
ArrayList<file> files = new ArrayList<>();
for (String s : ss)
if ((filter == null) || filter.accept(this, s))
files.add(new File(s, this));
return files.toArray(new File[files.size()]);
}
public File[] listFiles(FileFilter filter) {
String ss[] = list();
if (ss == null) return null;
ArrayList<file> files = new ArrayList<>();
for (String s : ss) {
File f = new File(s, this);
if ((filter == null) || filter.accept(f))
files.add(f);
}
return files.toArray(new File[files.size()]);
}
//创建目录
public boolean mkdir() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
if (isInvalid()) {
return false;
}
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);
}
if (dest == null) {
throw new NullPointerException();
}
if (this.isInvalid() || dest.isInvalid()) {
return false;
}
return fs.rename(this, dest);
}
//设置最后修改的世界
public boolean setLastModified(long time) {
if (time < 0) throw new IllegalArgumentException("Negative time");
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
if (isInvalid()) {
return false;
}
return fs.setLastModifiedTime(this, time);
}
//设置为只读
public boolean setReadOnly() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
if (isInvalid()) {
return false;
}
return fs.setReadOnly(this);
}
//设置可写
public boolean setWritable(boolean writable, boolean ownerOnly) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
if (isInvalid()) {
return false;
}
return fs.setPermission(this, FileSystem.ACCESS_WRITE, writable, ownerOnly);
}
public boolean setWritable(boolean writable) {
return setWritable(writable, true);
}
//设置可读
public boolean setReadable(boolean readable, boolean ownerOnly) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
if (isInvalid()) {
return false;
}
return fs.setPermission(this, FileSystem.ACCESS_READ, readable, ownerOnly);
}
//
public boolean setReadable(boolean readable) {
return setReadable(readable, true);
}
//设置可执行
public boolean setExecutable(boolean executable, boolean ownerOnly) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
if (isInvalid()) {
return false;
}
return fs.setPermission(this, FileSystem.ACCESS_EXECUTE, executable, ownerOnly);
}
public boolean setExecutable(boolean executable) {
return setExecutable(executable, true);
}
//能否执行
public boolean canExecute() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkExec(path);
}
if (isInvalid()) {
return false;
}
return fs.checkAccess(this, FileSystem.ACCESS_EXECUTE);
}
/* -- Filesystem interface -- */
//从根目录获得文件
public static File[] listRoots() {
return fs.listRoots();
}
/* -- Disk usage -- */
//获得所有的空间
public long getTotalSpace() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
sm.checkRead(path);
}
if (isInvalid()) {
return 0L;
}
return fs.getSpace(this, FileSystem.SPACE_TOTAL);
}
//为使用空间
public long getFreeSpace() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
sm.checkRead(path);
}
if (isInvalid()) {
return 0L;
}
return fs.getSpace(this, FileSystem.SPACE_FREE);
}
//可用空间
public long getUsableSpace() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
sm.checkRead(path);
}
if (isInvalid()) {
return 0L;
}
return fs.getSpace(this, FileSystem.SPACE_USABLE);
}
/* -- Temporary files -- */
private static class TempDirectory {
private TempDirectory() { }
// temporary directory location
private static final File tmpdir = new File(AccessController
.doPrivileged(new GetPropertyAction("java.io.tmpdir")));
static File location() {
return tmpdir;
}
// file name generation
private static final SecureRandom random = new SecureRandom();
static File generateFile(String prefix, String suffix, File dir)
throws IOException
{
long n = random.nextLong();
if (n == Long.MIN_VALUE) {
n = 0; // corner case
} else {
n = Math.abs(n);
}
// Use only the file name from the supplied prefix
prefix = (new File(prefix)).getName();
String name = prefix + Long.toString(n) + suffix;
File f = new File(dir, name);
if (!name.equals(f.getName()) || f.isInvalid()) {
if (System.getSecurityManager() != null)
throw new IOException("Unable to create temporary file");
else
throw new IOException("Unable to create temporary file, " + f);
}
return f;
}
}
//创建零时文件
public static File createTempFile(String prefix, String suffix,File directory)throws IOException
{
if (prefix.length() < 3)
throw new IllegalArgumentException("Prefix string too short");
if (suffix == null)
suffix = ".tmp";
File tmpdir = (directory != null) ? directory: TempDirectory.location();
SecurityManager sm = System.getSecurityManager();
File f;
do {
f = TempDirectory.generateFile(prefix, suffix, tmpdir);
if (sm != null) {
try {
sm.checkWrite(f.getPath());
} catch (SecurityException se) {
// don't reveal temporary directory location
if (directory == null)
throw new SecurityException("Unable to create temporary file");
throw se;
}
}
} while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0);
if (!fs.createFileExclusively(f.getPath()))
throw new IOException("Unable to create temporary file");
return f;
}
//空临时文件
public static File createTempFile(String prefix, String suffix)throws IOException
{
return createTempFile(prefix, suffix, null);
}
/* -- Basic infrastructure -- */
//比较
public int compareTo(File pathname) {
return fs.compare(this, pathname);
}
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof File)) {
return compareTo((File)obj) == 0;
}
return false;
}
public int hashCode() {
return fs.hashCode(this);
}
public String toString() {
return getPath();
}
private synchronized void writeObject(java.io.ObjectOutputStream s)throws IOException
{
s.defaultWriteObject();
s.writeChar(separatorChar); // Add the separator character
}
private synchronized void readObject(java.io.ObjectInputStream s)throws IOException, ClassNotFoundException
{
ObjectInputStream.GetField fields = s.readFields();
String pathField = (String)fields.get("path", null);
char sep = s.readChar(); // read the previous separator char
if (sep != separatorChar)
pathField = pathField.replace(sep, separatorChar);
String path = fs.normalize(pathField);
UNSAFE.putObject(this, PATH_OFFSET, path);
UNSAFE.putIntVolatile(this, PREFIX_LENGTH_OFFSET, fs.prefixLength(path));
}
private static final long PATH_OFFSET;
private static final long PREFIX_LENGTH_OFFSET;
private static final sun.misc.Unsafe UNSAFE;
static {
try {
sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
PATH_OFFSET = unsafe.objectFieldOffset(
File.class.getDeclaredField("path"));
PREFIX_LENGTH_OFFSET = unsafe.objectFieldOffset(
File.class.getDeclaredField("prefixLength"));
UNSAFE = unsafe;
} catch (ReflectiveOperationException e) {
throw new Error(e);
}
}
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = 301077366599181567L;
// -- Integration with java.nio.file --
private volatile transient Path filePath;
public Path toPath() {
Path result = filePath;
if (result == null) {
synchronized (this) {
result = filePath;
if (result == null) {
result = FileSystems.getDefault().getPath(path);
filePath = result;
}
}
}
return result;
}
}