Java-Io之文件File
File是“文件”和“目录路径名”的抽象表示形式。File之间继承Object,实现了Serializable和Comparable接口,因此文件支持File对象序列化,同时File对象之间可以比较大小。
File类中主要的函数有:
// 静态成员 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 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();
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();
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<File>
{
//获得当前系统平台的文件系统
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</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;
/**
* 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</code>. 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>':'</code>; on Microsoft Windows systems it
* is <code>';'</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}</code>.
*/
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</code> 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</code> argument is <code>null</code>
*/
//通过路径名构造一个对象
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;
}
}
Java-Io之文件File的更多相关文章
- java io读写文件
java io读写文件相关阅读:http://www.cnblogs.com/wing011203/archive/2013/05/03/3056535.html public class DemoI ...
- java(IO)读写文件乱码转换UTF-8问题
java(IO)读写文件乱码转换UTF-8问题 读取文件 String Content = ""; // 文件很长的话建议使用StringBuffer try { FileInpu ...
- Java IO体系之File类浅析
Java IO体系之File类浅析 一.File类介绍 位于java.io下的Java File类以抽象的方式代表文件名和目录路径名.该类主要用于文件和目录的创建.文件的查找和文件的删除等.File对 ...
- Java IO 流-- 文件拷贝
IO流操作套路: 1.创建源: 2.选择流: 3.操作: 4.释放资源 上代码: package com.xzlf.io; import java.io.File; import java.io.Fi ...
- Java IO :文件
在java应用程序中,文件是一种常用的数据源或者存储数据的媒介.所以这一小节将会对Java中文件的使用做一个简短的概述.这里只提供一些必要的知识点. 通过Java IO读文件 如果你需要在不同端之间读 ...
- Java IO流中 File文件对象与Properties类(四)
File类 用来将文件或目录封装成对象 方便对文件或目录信息进行处理 File对象可以作为参数传递给流进行操作 File类常用方法 创建 booleancreateNewFile():创建新文件,如果 ...
- 系统学习 Java IO (三)----文件类 File
目录:系统学习 Java IO---- 目录,概览 Java IO API 中的 File 类可以访问基础文件系统. 使用 File 类,可以: 检查文件或目录是否存在. 如果目录不存在,创建一个目录 ...
- java io学习之File类
1.先看下四个静态变量 static String pathSeparator The system-dependent path-separator character, represented a ...
- java io知识点汇总FIle类
1.路径分隔符问题: 因为java有跨平台行,而在windows和linux中的目录分隔符是不同的.windows是"\" 而linux是"/" 所以必须想办 ...
- 【Java IO流】File类的使用
File类的使用 Java中的File类是在java.io.File中,Java.IO.File类表示文件或目录. File类只用于表示文件(目录)的信息(名称.大小等),不能用于文件内容的访问. 一 ...
随机推荐
- [Luogu 1516] 青蛙的约会
Description 两只青蛙在网上相识了,它们聊得很开心,于是觉得很有必要见一面.它们很高兴地发现它们住在同一条纬度线上,于是它们约定各自朝西跳,直到碰面为止.可是它们出发之前忘记了一件很重要的事 ...
- C# IE浏览器
引用Microsoft HTML Object Library 引用 -> com -> Microsoft HTML Object Library 引用后,显示如图 1.判断ie浏览器是 ...
- c++自定义类型
/* --自定义数据类型 结构体 共用体 共用体的数据成员在存储数据时共享存储空间,修改一个成员也会改变另一个成员的值 枚举型 如果要使变量只能使用有限的几个值,则应当使用枚举体.之所以叫枚举体,就是 ...
- 嫌我的键盘的backspace太小,就尝试了一下改键工具--keyTweak
KeyTweak是一个很简单的键盘remap小工具,主要功能就是可以让我们选择某个按键并重新赋予该按键一个新的功能.如果哪天你的键盘某个重要的键坏掉了,可以通过这个免费的软件来重新定义该按键的功能.譬 ...
- python if判断语句&计算
python对缩进要求严格,代码块里的缩进必须一样,可以常用 tab键 表示4个空格 if 条件: 代码块 else: if判断语句如下: 1 print("吃饭,喝水,回家") ...
- Vue 波纹按钮组件
代码链接:https://github.com/zhangKunUserGit/vue-component 效果图: 大家可以在线运行: https://zhangkunusergit.github. ...
- Django 跨域请求处理
参考https://blog.csdn.net/qq_27068845/article/details/73007155 http://blog.51cto.com/aaronsa/2071108 d ...
- MySQL系列教程(一)
摘要 MySQL的最初的核心思想,主要是开源.简便易用.其开发可追溯至1985年,而第一个内部发行版本诞生,已经是1995年.到1998年,MySQL已经可以支持10中操作系统了,其中就包括win平台 ...
- android launcher 之踩到的坑
需求: 1. 用android系统launcher 隐藏主菜单 所有应用显示在桌面 即workspace上: 2.隐藏launcher上方默认的google search: 3.切换一套launche ...
- protobuf中的枚举缺省值应该为UNKNOWN
protobuf中的枚举缺省值应该为UNKNOWN(金庆的专栏)proto3中的枚举值为了与proto2兼容,要求缺省值固定为第1个,值为0.proto2中并没有规定对范围之外的枚举值的处理,而pro ...