認識Java中關於文件的兩個類FileSystem和FIle類,兩篇文章很長,建議精讀的用鼠標滾輪滑動,泛讀或看方法使用的直接單擊拖動到最底部方法總結部分。
package java.io;
import java.lang.annotation.Native;
/**
* Package-private abstract class for the local filesystem abstraction.
*/
abstract class FileSystem {
/* -- Normalization and construction -- */
/**
* Return the local filesystem's name-separator character.
*/
public abstract char getSeparator();
/**
* Return the local filesystem's path-separator character.
*/
public abstract char getPathSeparator();
/**
* Convert the given pathname string to normal form. If the string is
* already in normal form then it is simply returned.
*/
public abstract String normalize(String path);
/**
* Compute the length of this pathname string's prefix. The pathname
* string must be in normal form.
*/
public abstract int prefixLength(String path);
/**
* Resolve the child pathname string against the parent.
* Both strings must be in normal form, and the result
* will be in normal form.
*/
public abstract String resolve(String parent, String child);
/**
* Return the parent pathname string to be used when the parent-directory
* argument in one of the two-argument File constructors is the empty
* pathname.
*/
public abstract String getDefaultParent();
/**
* Post-process the given URI path string if necessary. This is used on
* win32, e.g., to transform "/c:/foo" into "c:/foo". The path string
* still has slash separators; code in the File class will translate them
* after this method returns.
*/
public abstract String fromURIPath(String path);
/* -- Path operations -- */
/**
* Tell whether or not the given abstract pathname is absolute.
*/
public abstract boolean isAbsolute(File f);
/**
* Resolve the given abstract pathname into absolute form. Invoked by the
* getAbsolutePath and getCanonicalPath methods in the File class.
*/
public abstract String resolve(File f);
public abstract String canonicalize(String path) throws IOException;
/* -- Attribute accessors -- */
/* Constants for simple boolean attributes */
@Native public static final int BA_EXISTS = 0x01;
@Native public static final int BA_REGULAR = 0x02;
@Native public static final int BA_DIRECTORY = 0x04;
@Native public static final int BA_HIDDEN = 0x08;
/**
* Return the simple boolean attributes for the file or directory denoted
* by the given abstract pathname, or zero if it does not exist or some
* other I/O error occurs.
*/
public abstract int getBooleanAttributes(File f);
@Native public static final int ACCESS_READ = 0x04;
@Native public static final int ACCESS_WRITE = 0x02;
@Native public static final int ACCESS_EXECUTE = 0x01;
public static final int ACCESS_OK = 0x08;
/**
* Check whether the file or directory denoted by the given abstract
* pathname may be accessed by this process. The second argument specifies
* which access, ACCESS_READ, ACCESS_WRITE or ACCESS_EXECUTE, to check.
* Return false if access is denied or an I/O error occurs
*/
public abstract boolean checkAccess(File f, int access);
/**
* Set on or off the access permission (to owner only or to all) to the file
* or directory denoted by the given abstract pathname, based on the parameters
* enable, access and oweronly.
*/
public abstract boolean setPermission(File f, int access, boolean enable, boolean owneronly);
/**
* Return the time at which the file or directory denoted by the given
* abstract pathname was last modified, or zero if it does not exist or
* some other I/O error occurs.
*/
public abstract long getLastModifiedTime(File f);
/**
* Return the length in bytes of the file denoted by the given abstract
* pathname, or zero if it does not exist, is a directory, or some other
* I/O error occurs.
*/
public abstract long getLength(File f);
/* -- File operations -- */
/**
* Create a new empty file with the given pathname. Return
* <code>true</code> if the file was created and <code>false</code> if a
* file or directory with the given pathname already exists. Throw an
* IOException if an I/O error occurs.
*/
public abstract boolean createFileExclusively(String pathname)
throws IOException;
/**
* Delete the file or directory denoted by the given abstract pathname,
* returning <code>true</code> if and only if the operation succeeds.
*/
public abstract boolean delete(File f);
/**
* List the elements of the directory denoted by the given abstract
* pathname. Return an array of strings naming the elements of the
* directory if successful; otherwise, return <code>null</code>.
*/
public abstract String[] list(File f);
/**
* Create a new directory denoted by the given abstract pathname,
* returning <code>true</code> if and only if the operation succeeds.
*/
public abstract boolean createDirectory(File f);
/**
* Rename the file or directory denoted by the first abstract pathname to
* the second abstract pathname, returning <code>true</code> if and only if
* the operation succeeds.
*/
public abstract boolean rename(File f1, File f2);
/**
* Set the last-modified time of the file or directory denoted by the
* given abstract pathname, returning <code>true</code> if and only if the
* operation succeeds.
*/
public abstract boolean setLastModifiedTime(File f, long time);
/**
* Mark the file or directory denoted by the given abstract pathname as
* read-only, returning <code>true</code> if and only if the operation
* succeeds.
*/
public abstract boolean setReadOnly(File f);
/* -- Filesystem interface -- */
/**
* List the available filesystem roots.
*/
public abstract File[] listRoots();
/* -- Disk usage -- */
@Native public static final int SPACE_TOTAL = 0;
@Native public static final int SPACE_FREE = 1;
@Native public static final int SPACE_USABLE = 2;
public abstract long getSpace(File f, int t);
/* -- Basic infrastructure -- */
/**
* Compare two abstract pathnames lexicographically.
*/
public abstract int compare(File f1, File f2);
/**
* Compute the hash code of an abstract pathname.
*/
public abstract int hashCode(File f);
// Flags for enabling/disabling performance optimizations for file
// name canonicalization
static boolean useCanonCaches = true;
static boolean useCanonPrefixCache = true;
private static boolean getBooleanProperty(String prop, boolean defaultVal) {
String val = System.getProperty(prop);
if (val == null) return defaultVal;
if (val.equalsIgnoreCase("true")) {
return true;
} else {
return false;
}
}
static {
useCanonCaches = getBooleanProperty("sun.io.useCanonCaches",
useCanonCaches);
useCanonPrefixCache = getBooleanProperty("sun.io.useCanonPrefixCache",
useCanonPrefixCache);
}
}
File類如下:
package java.io;
import java.net.URI;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.ArrayList;
import java.security.AccessController;
import java.nio.file.Path;
import java.nio.file.FileSystems;
import sun.security.action.GetPropertyAction;
/**
* An abstract representation of file and directory pathnames.
* ......
*/
public class File implements Serializable, Comparable<File>{
/**
* The FileSystem object representing the platform's local file system.
*/
private static final FileSystem fs = DefaultFileSystem.getFileSystem();
/**
* This abstract pathname's normalized pathname string. A normalized
* pathname string uses the default name-separator character and does not
* contain any duplicate or redundant separators.
*
* @serial
*/
private final String path;
/**
* Enum type that indicates the status of a file path.
*/
private static enum PathStatus { INVALID, CHECKED };
/**
* The flag indicating whether the file path is invalid.
*/
private transient PathStatus status = null;
/**
* Check if the file has an invalid path. Currently, the inspection of
* a file path is very limited, and it only covers Nul character check.
* Returning true means the path is definitely invalid/garbage. But
* returning false does not guarantee that the path is valid.
*
* @return true if the file path is invalid.
*/
final boolean isInvalid() {
if (status == null) {
status = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED
: PathStatus.INVALID;
}
return status == PathStatus.INVALID;
}
/**
* The length of this abstract pathname's prefix, or zero if it has no
* prefix.
*/
private final transient int prefixLength;
/**
* Returns the length of this abstract pathname's prefix.
* For use by FileSystem classes.
*/
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);
}
/* Note: The two-argument File constructors do not interpret an empty
parent abstract pathname as the current user directory. An empty parent
instead causes the child to be resolved against the system-dependent
directory defined by the FileSystem.getDefaultParent method. On Unix
this default is "/", while on Microsoft Windows it is "\\". This is required for
compatibility with the original behavior of this class. */
/**
* Creates a new <code>File</code> instance from a parent pathname string
* and a child pathname string.
*
* <p> If <code>parent</code> is <code>null</code> then the new
* <code>File</code> instance is created as if by invoking the
* single-argument <code>File</code> constructor on the given
* <code>child</code> pathname string.
*
* <p> Otherwise the <code>parent</code> pathname string is taken to denote
* a directory, and the <code>child</code> pathname string is taken to
* denote either a directory or a file. If the <code>child</code> pathname
* string is absolute then it is converted into a relative pathname in a
* system-dependent way. If <code>parent</code> is the empty string then
* the new <code>File</code> instance is created by converting
* <code>child</code> into an abstract pathname and resolving the result
* against a system-dependent default directory. Otherwise each pathname
* string is converted into an abstract pathname and the child abstract
* pathname is resolved against the parent.
*
* @param parent The parent pathname string
* @param child The child pathname string
* @throws NullPointerException
* If <code>child</code> is <code>null</code>
*/
public File(String parent, String child) {
if (child == null) {
throw new NullPointerException();
}
if (parent != null && !parent.isEmpty()) {
this.path = fs.resolve(fs.normalize(parent),
fs.normalize(child));
} else {
this.path = fs.normalize(child);
}
this.prefixLength = fs.prefixLength(this.path);
}
/**
* Creates a new <code>File</code> instance from a parent abstract
* pathname and a child pathname string.
*
* <p> If <code>parent</code> is <code>null</code> then the new
* <code>File</code> instance is created as if by invoking the
* single-argument <code>File</code> constructor on the given
* <code>child</code> pathname string.
*
* <p> Otherwise the <code>parent</code> abstract pathname is taken to
* denote a directory, and the <code>child</code> pathname string is taken
* to denote either a directory or a file. If the <code>child</code>
* pathname string is absolute then it is converted into a relative
* pathname in a system-dependent way. If <code>parent</code> is the empty
* abstract pathname then the new <code>File</code> instance is created by
* converting <code>child</code> into an abstract pathname and resolving
* the result against a system-dependent default directory. Otherwise each
* pathname string is converted into an abstract pathname and the child
* abstract pathname is resolved against the parent.
*
* @param parent The parent abstract pathname
* @param child The child pathname string
* @throws NullPointerException
* If <code>child</code> is <code>null</code>
*/
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);
}
/**
* Creates a new <tt>File</tt> instance by converting the given
* <tt>file:</tt> URI into an abstract pathname.
*
* <p> The exact form of a <tt>file:</tt> URI is system-dependent, hence
* the transformation performed by this constructor is also
* system-dependent.
*
* <p> For a given abstract pathname <i>f</i> it is guaranteed that
*
* <blockquote><tt>
* new File(</tt><i> f</i><tt>.{@link #toURI() toURI}()).equals(</tt><i> f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}())
* </tt></blockquote>
*
* so long as the original abstract pathname, the URI, and the new abstract
* pathname are all created in (possibly different invocations of) the same
* Java virtual machine. This relationship typically does not hold,
* however, when a <tt>file:</tt> URI that is created in a virtual machine
* on one operating system is converted into an abstract pathname in a
* virtual machine on a different operating system.
*
* @param uri
* An absolute, hierarchical URI with a scheme equal to
* <tt>"file"</tt>, a non-empty path component, and undefined
* authority, query, and fragment components
*
* @throws NullPointerException
* If <tt>uri</tt> is <tt>null</tt>
*
* @throws IllegalArgumentException
* If the preconditions on the parameter do not hold
*
* @see #toURI()
* @see java.net.URI
* @since 1.4
*/
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);
}
/* -- Path-component accessors -- */
/**
* Returns the name of the file or directory denoted by this abstract
* pathname. This is just the last name in the pathname's name
* sequence. If the pathname's name sequence is empty, then the empty
* string is returned.
*
* @return The name of the file or directory denoted by this abstract
* pathname, or the empty string if this pathname's name sequence
* is empty
*/
public String getName() {
int index = path.lastIndexOf(separatorChar);
if (index < prefixLength) return path.substring(prefixLength);
return path.substring(index + 1);
}
/**
* Returns the pathname string of this abstract pathname's parent, or
* <code>null</code> if this pathname does not name a parent directory.
*
* <p> The <em>parent</em> of an abstract pathname consists of the
* pathname's prefix, if any, and each name in the pathname's name
* sequence except for the last. If the name sequence is empty then
* the pathname does not name a parent directory.
*
* @return The pathname string of the parent directory named by this
* abstract pathname, or <code>null</code> if this pathname
* does not name a parent
*/
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);
}
/**
* Returns the abstract pathname of this abstract pathname's parent,
* or <code>null</code> if this pathname does not name a parent
* directory.
*
* <p> The <em>parent</em> of an abstract pathname consists of the
* pathname's prefix, if any, and each name in the pathname's name
* sequence except for the last. If the name sequence is empty then
* the pathname does not name a parent directory.
*
* @return The abstract pathname of the parent directory named by this
* abstract pathname, or <code>null</code> if this pathname
* does not name a parent
*
* @since 1.2
*/
public File getParentFile() {
String p = this.getParent();
if (p == null) return null;
return new File(p, this.prefixLength);
}
/**
* Converts this abstract pathname into a pathname string. The resulting
* string uses the {@link #separator default name-separator character} to
* separate the names in the name sequence.
*
* @return The string form of this abstract pathname
*/
public String getPath() {
return path;
}
/* -- Path operations -- */
/**
* Tests whether this abstract pathname is absolute. The definition of
* absolute pathname is system dependent. On Android, absolute paths start with
* the character '/'.
*
* @return <code>true</code> if this abstract pathname is absolute,
* <code>false</code> otherwise
*/
public boolean isAbsolute() {
return fs.isAbsolute(this);
}
/**
* Returns the absolute path of this file. An absolute path is a path that starts at a root
* of the file system. On Android, there is only one root: {@code /}.
*
* <p>A common use for absolute paths is when passing paths to a {@code Process} as
* command-line arguments, to remove the requirement implied by relative paths, that the
* child must have the same working directory as its parent.
*
* @return The absolute pathname string denoting the same file or
* directory as this abstract pathname
*
* @see java.io.File#isAbsolute()
*/
public String getAbsolutePath() {
return fs.resolve(this);
}
/**
* Returns the absolute form of this abstract pathname. Equivalent to
* <code>new File(this.{@link #getAbsolutePath})</code>.
*
*/
public File getAbsoluteFile() {
String absPath = getAbsolutePath();
return new File(absPath, fs.prefixLength(absPath));
}
/**
* Returns the canonical pathname string of this abstract pathname.
*......
*/
public String getCanonicalPath() throws IOException {
if (isInvalid()) {
throw new IOException("Invalid file path");
}
return fs.canonicalize(fs.resolve(this));
}
/**
* Returns the canonical form of this abstract pathname. Equivalent to
* <code>new File(this.{@link #getCanonicalPath})</code>.
*
*/
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;
}
/**
* Converts this abstract pathname into a <code>file:</code> URL. The
* exact form of the URL is system-dependent. If it can be determined that
* the file denoted by this abstract pathname is a directory, then the
* resulting URL will end with a slash.
*......
*/
@Deprecated
public URL toURL() throws MalformedURLException {
if (isInvalid()) {
throw new MalformedURLException("Invalid file path");
}
return new URL("file", "", slashify(getAbsolutePath(),
getAbsoluteFile().isDirectory()));
}
/**
* Constructs a <tt>file:</tt> URI that represents this abstract pathname.
*
*......
*/
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 -- */
// Android-changed. Removed javadoc comment about special privileges
// that doesn't make sense on android
/**
* Tests whether the application can read the file denoted by this
* abstract pathname.
*
* @return <code>true</code> if and only if the file specified by this
* abstract pathname exists <em>and</em> can be read by the
* application; <code>false</code> otherwise
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
* method denies read access to the file
*/
public boolean canRead() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(path);
}
if (isInvalid()) {
return false;
}
return fs.checkAccess(this, FileSystem.ACCESS_READ);
}
// Android-changed. Removed javadoc comment about special privileges
// that doesn't make sense on android
/**
* Tests whether the application can modify the file denoted by this
* abstract pathname.
*
* @return <code>true</code> if and only if the file system actually
* contains a file denoted by this abstract pathname <em>and</em>
* the application is allowed to write to the file;
* <code>false</code> otherwise.
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
* method denies write access to the file
*/
public boolean canWrite() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
if (isInvalid()) {
return false;
}
return fs.checkAccess(this, FileSystem.ACCESS_WRITE);
}
/**
* Tests whether the file or directory denoted by this abstract pathname
* exists.
*
* @return <code>true</code> if and only if the file or directory denoted
* by this abstract pathname exists; <code>false</code> otherwise
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
* method denies read access to the file or directory
*/
public boolean exists() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(path);
}
if (isInvalid()) {
return false;
}
return fs.checkAccess(this, FileSystem.ACCESS_OK);
}
/**
* Tests whether the file denoted by this abstract pathname is a
* directory.
*
* <p> Where it is required to distinguish an I/O exception from the case
* that the file is not a directory, or where several attributes of the
* same file are required at the same time, then the {@link
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
* Files.readAttributes} method may be used.
*
* @return <code>true</code> if and only if the file denoted by this
* abstract pathname exists <em>and</em> is a directory;
* <code>false</code> otherwise
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
* method denies read access to the file
*/
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);
}
/**
* Tests whether the file denoted by this abstract pathname is a normal
* file. A file is <em>normal</em> if it is not a directory and, in
* addition, satisfies other system-dependent criteria. Any non-directory
* file created by a Java application is guaranteed to be a normal file.
*
* <p> Where it is required to distinguish an I/O exception from the case
* that the file is not a normal file, or where several attributes of the
* same file are required at the same time, then the {@link
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
* Files.readAttributes} method may be used.
*
* @return <code>true</code> if and only if the file denoted by this
* abstract pathname exists <em>and</em> is a normal file;
* <code>false</code> otherwise
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
* method denies read access to the file
*/
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);
}
/**
* Tests whether the file named by this abstract pathname is a hidden
* file. The exact definition of <em>hidden</em> is system-dependent. On
* UNIX systems, a file is considered to be hidden if its name begins with
* a period character (<code>'.'</code>). On Microsoft Windows systems, a file is
* considered to be hidden if it has been marked as such in the filesystem.
*
* @return <code>true</code> if and only if the file denoted by this
* abstract pathname is hidden according to the conventions of the
* underlying platform
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
* method denies read access to the file
*
* @since 1.2
*/
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);
}
/**
* Returns the time that the file denoted by this abstract pathname was
* last modified.
*
* <p> Where it is required to distinguish an I/O exception from the case
* where {@code 0L} is returned, or where several attributes of the
* same file are required at the same time, or where the time of last
* access or the creation time are required, then the {@link
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
* Files.readAttributes} method may be used.
*
* @return A <code>long</code> value representing the time the file was
* last modified, measured in milliseconds since the epoch
* (00:00:00 GMT, January 1, 1970), or <code>0L</code> if the
* file does not exist or if an I/O error occurs
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
* method denies read access to the file
*/
public long lastModified() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(path);
}
if (isInvalid()) {
return 0L;
}
return fs.getLastModifiedTime(this);
}
/**
* Returns the length of the file denoted by this abstract pathname.
* The return value is unspecified if this pathname denotes a directory.
*
* <p> Where it is required to distinguish an I/O exception from the case
* that {@code 0L} is returned, or where several attributes of the same file
* are required at the same time, then the {@link
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
* Files.readAttributes} method may be used.
*
* @return The length, in bytes, of the file denoted by this abstract
* pathname, or <code>0L</code> if the file does not exist. Some
* operating systems may return <code>0L</code> for pathnames
* denoting system-dependent entities such as devices or pipes.
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
* method denies read access to the file
*/
public long length() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(path);
}
if (isInvalid()) {
return 0L;
}
return fs.getLength(this);
}
/* -- File operations -- */
/**
* Atomically creates a new, empty file named by this abstract pathname if
* and only if a file with this name does not yet exist. The check for the
* existence of the file and the creation of the file if it does not exist
* are a single operation that is atomic with respect to all other
* filesystem activities that might affect the file.
* <P>
* Note: this method should <i>not</i> be used for file-locking, as
* the resulting protocol cannot be made to work reliably. The
* {@link java.nio.channels.FileLock FileLock}
* facility should be used instead.
*
* @return <code>true</code> if the named file does not exist and was
* successfully created; <code>false</code> if the named file
* already exists
*
* @throws IOException
* If an I/O error occurred
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
* method denies write access to the file
*
* @since 1.2
*/
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);
}
/**
* Deletes the file or directory denoted by this abstract pathname. If
* this pathname denotes a directory, then the directory must be empty in
* order to be deleted.
*
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
* java.nio.file.Files#delete(Path) delete} method to throw an {@link IOException}
* when a file cannot be deleted. This is useful for error reporting and to
* diagnose why a file cannot be deleted.
*
* @return <code>true</code> if and only if the file or directory is
* successfully deleted; <code>false</code> otherwise
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkDelete}</code> method denies
* delete access to the file
*/
public boolean delete() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkDelete(path);
}
if (isInvalid()) {
return false;
}
return fs.delete(this);
}
/**
* Requests that the file or directory denoted by this abstract
* pathname be deleted when the virtual machine terminates.
* Files (or directories) are deleted in the reverse order that
* they are registered. Invoking this method to delete a file or
* directory that is already registered for deletion has no effect.
* Deletion will be attempted only for normal termination of the
* virtual machine, as defined by the Java Language Specification.
*
*/
public void deleteOnExit() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkDelete(path);
}
if (isInvalid()) {
return;
}
DeleteOnExitHook.add(path);
}
/**
* Returns an array of strings naming the files and directories in the
* directory denoted by this abstract pathname.
*
* <p> If this abstract pathname does not denote a directory, then this
* method returns {@code null}. Otherwise an array of strings is
* returned, one for each file or directory in the directory. Names
* denoting the directory itself and the directory's parent directory are
* not included in the result. Each string is a file name rather than a
* complete path.
*
* <p> There is no guarantee that the name strings in the resulting array
* will appear in any specific order; they are not, in particular,
* guaranteed to appear in alphabetical order.
*
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
* java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method to
* open a directory and iterate over the names of the files in the directory.
* This may use less resources when working with very large directories, and
* may be more responsive when working with remote directories.
*
* @return An array of strings naming the files and directories in the
* directory denoted by this abstract pathname. The array will be
* empty if the directory is empty. Returns {@code null} if
* this abstract pathname does not denote a directory, or if an
* I/O error occurs.
*
* @throws SecurityException
* If a security manager exists and its {@link
* SecurityManager#checkRead(String)} method denies read access to
* the directory
*/
public String[] list() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(path);
}
if (isInvalid()) {
return null;
}
return fs.list(this);
}
/**
* Returns an array of strings naming the files and directories in the
* directory denoted by this abstract pathname that satisfy the specified
* filter. The behavior of this method is the same as that of the
* {@link #list()} method, except that the strings in the returned array
* must satisfy the filter. If the given {@code filter} is {@code null}
* then all names are accepted. Otherwise, a name satisfies the filter if
* and only if the value {@code true} results when the {@link
* FilenameFilter#accept FilenameFilter.accept(File, String)} method
* of the filter is invoked on this abstract pathname and the name of a
* file or directory in the directory that it denotes.
*
* @param filter
* A filename filter
*
* @return An array of strings naming the files and directories in the
* directory denoted by this abstract pathname that were accepted
* by the given {@code filter}. The array will be empty if the
* directory is empty or if no names were accepted by the filter.
* Returns {@code null} if this abstract pathname does not denote
* a directory, or if an I/O error occurs.
*
* @throws SecurityException
* If a security manager exists and its {@link
* SecurityManager#checkRead(String)} method denies read access to
* the directory
*
* @see java.nio.file.Files#newDirectoryStream(Path,String)
*/
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()]);
}
/**
* Creates the directory named by this abstract pathname.
*
* @return <code>true</code> if and only if the directory was
* created; <code>false</code> otherwise
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
* method does not permit the named directory to be created
*/
public boolean mkdir() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
if (isInvalid()) {
return false;
}
return fs.createDirectory(this);
}
/**
* Creates the directory named by this abstract pathname, including any
* necessary but nonexistent parent directories. Note that if this
* operation fails it may have succeeded in creating some of the necessary
* parent directories.
*
* @return <code>true</code> if and only if the directory was created,
* along with all necessary parent directories; <code>false</code>
* otherwise
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
* method does not permit verification of the existence of the
* named directory and all necessary parent directories; or if
* the <code>{@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
* method does not permit the named directory and all necessary
* parent directories to be created
*/
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());
}
/**
* Renames the file denoted by this abstract pathname.
*
* <p>Many failures are possible. Some of the more likely failures include:
* <ul>
* <li>Write permission is required on the directories containing both the source and
* destination paths.
* <li>Search permission is required for all parents of both paths.
* <li>Both paths be on the same mount point. On Android, applications are most likely to hit
* this restriction when attempting to copy between internal storage and an SD card.
* </ul>
*
* <p>The return value should always be checked to make sure
* that the rename operation was successful.
*
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
* java.nio.file.Files#move move} method to move or rename a file in a
* platform independent manner.
*
* @param dest The new abstract pathname for the named file
*
* @return <code>true</code> if and only if the renaming succeeded;
* <code>false</code> otherwise
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
* method denies write access to either the old or new pathnames
*
* @throws NullPointerException
* If parameter <code>dest</code> is <code>null</code>
*/
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);
}
/**
* Sets the last-modified time of the file or directory named by this
* abstract pathname.
* ......
*/
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);
}
// Android-changed. Removed javadoc comment about special privileges
// that doesn't make sense on android
/**
* Marks the file or directory named by this abstract pathname so that
* only read operations are allowed. After invoking this method the file
* or directory will not change until it is either deleted or marked
* to allow write access. Whether or not a read-only file or
* directory may be deleted depends upon the underlying system.
* ......
*/
public boolean setReadOnly() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
if (isInvalid()) {
return false;
}
return fs.setReadOnly(this);
}
// Android-changed. Removed javadoc comment about special privileges
// that doesn't make sense on android
/**
* Sets the owner's or everybody's write permission for this abstract
* pathname.
* .......
*/
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);
}
// Android-changed. Removed javadoc comment about special privileges
// that doesn't make sense on android
/**
* A convenience method to set the owner's write permission for this abstract
* pathname.
*
* ......
*/
public boolean setWritable(boolean writable) {
return setWritable(writable, true);
}
// Android-changed. Removed javadoc comment about special privileges
// that doesn't make sense on android
/**
* Sets the owner's or everybody's read permission for this abstract
* pathname.
*
* <p> The {@link java.nio.file.Files} class defines methods that operate on
* file attributes including file permissions. This may be used when finer
* manipulation of file permissions is required.
*
*/
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);
}
// Android-changed. Removed javadoc comment about special privileges
// that doesn't make sense on android
/**
* A convenience method to set the owner's read permission for this abstract
* pathname.
*/
public boolean setReadable(boolean readable) {
return setReadable(readable, true);
}
// Android-changed. Removed javadoc comment about special privileges
// that doesn't make sense on android
/**
* Sets the owner's or everybody's execute permission for this abstract
* pathname.
*
* <p> The {@link java.nio.file.Files} class defines methods that operate on
* file attributes including file permissions. This may be used when finer
* manipulation of file permissions is required. .....
*/
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);
}
// Android-changed. Removed javadoc comment about special privileges
// that doesn't make sense on android
/**
* A convenience method to set the owner's execute permission for this
* abstract pathname.
*.......
*/
public boolean setExecutable(boolean executable) {
return setExecutable(executable, true);
}
// Android-changed. Removed javadoc comment about special privileges
// that doesn't make sense on android
/**
* Tests whether the application can execute the file denoted by this
* abstract pathname.
*
* @return <code>true</code> if and only if the abstract pathname exists
* <em>and</em> the application is allowed to execute the file
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkExec(java.lang.String)}</code>
* method denies execute access to the file
*
* @since 1.6
*/
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 -- */
/**
* Returns the file system roots. On Android and other Unix systems, there is
* a single root, {@code /}.
*/
public static File[] listRoots() {
return fs.listRoots();
}
/* -- Disk usage -- */
/**
* Returns the size of the partition <a href="#partName">named</a> by this
* abstract pathname.
*......
*/
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);
}
/**
* Returns the number of unallocated bytes in the partition <a
* href="#partName">named</a> by this abstract path name.
*......
*/
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);
}
/**
* Returns the number of bytes available to this virtual machine on the
* partition <a href="#partName">named</a> by this abstract pathname. When
* possible, this method checks for write permissions and other operating
* system restrictions and will therefore usually provide a more accurate
* estimate of how much new data can actually be written than {@link
* #getFreeSpace}.....
*/
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() { }
// Android-changed: Don't cache java.io.tmpdir value
// 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
static File generateFile(String prefix, String suffix, File dir)
throws IOException
{
// Android-changed: Use Math.randomIntInternal. This (pseudo) random number
// is initialized post-fork
long n = Math.randomLongInternal();
if (n == Long.MIN_VALUE) {
n = 0; // corner case
} else {
n = Math.abs(n);
}
// Android-changed: Reject invalid file prefixes
// 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;
}
}
/**
* <p> Creates a new empty file in the specified directory, using the
* given prefix and suffix strings to generate its name.
* A different value may be given to this system property when the Java virtual machine
* is invoked, but programmatic changes to this property are not guaranteed
* to have any effect upon the temporary directory used by this method.
*
* @param prefix The prefix string to be used in generating the file's
* name; must be at least three characters long
*
* @param suffix The suffix string to be used in generating the file's
* name; may be <code>null</code>, in which case the
* suffix <code>".tmp"</code> will be used
*
* @param directory The directory in which the file is to be created, or
* <code>null</code> if the default temporary-file
* directory is to be used
*
* @return An abstract pathname denoting a newly-created empty file
*
* @throws IllegalArgumentException
* If the <code>prefix</code> argument contains fewer than three
* characters
*
* @throws IOException If a file could not be created
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
* method does not allow a file to be created
*
* @since 1.2
*/
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
: new File(System.getProperty("java.io.tmpdir", "."));
//SecurityManager sm = System.getSecurityManager();
File f;
do {
f = TempDirectory.generateFile(prefix, suffix, tmpdir);
// Android change: sm is always null on android
// 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;
}
/**
* Creates an empty file in the default temporary-file directory, using
* the given prefix and suffix to generate its name. Invoking this method
* is equivalent to invoking <code>{@link #createTempFile(java.lang.String,
* java.lang.String, java.io.File)
* createTempFile(prefix, suffix, null)}</code>.
*
* <p> The {@link
* java.nio.file.Files#createTempFile(String,String,java.nio.file.attribute.FileAttribute[])
* Files.createTempFile} method provides an alternative method to create an
* empty file in the temporary-file directory. Files created by that method
* may have more restrictive access permissions to files created by this
* method and so may be more suited to security-sensitive applications.
*
* @param prefix The prefix string to be used in generating the file's
* name; must be at least three characters long
*
* @param suffix The suffix string to be used in generating the file's
* name; may be <code>null</code>, in which case the
* suffix <code>".tmp"</code> will be used
*
* @return An abstract pathname denoting a newly-created empty file
*
* @throws IllegalArgumentException
* If the <code>prefix</code> argument contains fewer than three
* characters
*
* @throws IOException If a file could not be created
*
* @throws SecurityException
* If a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
* method does not allow a file to be created
*
* @since 1.2
* @see java.nio.file.Files#createTempDirectory(String,FileAttribute[])
*/
public static File createTempFile(String prefix, String suffix)
throws IOException
{
return createTempFile(prefix, suffix, null);
}
/* -- Basic infrastructure -- */
/**
* Compares two abstract pathnames lexicographically. The ordering
* defined by this method depends upon the underlying system. On UNIX
* systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows
* systems it is not.
*
* @param pathname The abstract pathname to be compared to this abstract
* pathname
*
* @return Zero if the argument is equal to this abstract pathname, a
* value less than zero if this abstract pathname is
* lexicographically less than the argument, or a value greater
* than zero if this abstract pathname is lexicographically
* greater than the argument
*
* @since 1.2
*/
public int compareTo(File pathname) {
return fs.compare(this, pathname);
}
/**
* Tests this abstract pathname for equality with the given object.
* Returns <code>true</code> if and only if the argument is not
* <code>null</code> and is an abstract pathname that denotes the same file
* or directory as this abstract pathname. Whether or not two abstract
* pathnames are equal depends upon the underlying system. On UNIX
* systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows
* systems it is not.
*
* @param obj The object to be compared with this abstract pathname
*
* @return <code>true</code> if and only if the objects are the same;
* <code>false</code> otherwise
*/
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof File)) {
return compareTo((File)obj) == 0;
}
return false;
}
/**
* Computes a hash code for this abstract pathname. Because equality of
* abstract pathnames is inherently system-dependent, so is the computation
* of their hash codes. On UNIX systems, the hash code of an abstract
* pathname is equal to the exclusive <em>or</em> of the hash code
* of its pathname string and the decimal value
* <code>1234321</code>. On Microsoft Windows systems, the hash
* code is equal to the exclusive <em>or</em> of the hash code of
* its pathname string converted to lower case and the decimal
* value <code>1234321</code>. Locale is not taken into account on
* lowercasing the pathname string.
*
* @return A hash code for this abstract pathname
*/
public int hashCode() {
return fs.hashCode(this);
}
/**
* Returns the pathname string of this abstract pathname. This is just the
* string returned by the <code>{@link #getPath}</code> method.
*
* @return The string form of this abstract pathname
*/
public String toString() {
return getPath();
}
/**
* WriteObject is called to save this filename.
* The separator character is saved also so it can be replaced
* in case the path is reconstituted on a different host type.
* <p>
* @serialData Default fields followed by separator character.
*/
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
s.writeChar(separatorChar); // Add the separator character
}
/**
* readObject is called to restore this filename.
* The original separator character is read. If it is different
* than the separator character on this system, then the old separator
* is replaced by the local separator.
*/
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;
/**
* Returns a {@link Path java.nio.file.Path} object constructed from the
* this abstract path. The resulting {@code Path} is associated with the
* {@link java.nio.file.FileSystems#getDefault default-filesystem}.
* ......
* @since 1.7
* @see Path#toFile
*/
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;
}
}
方法總結部分
下面總結的方法均來自上面兩個類,想看源碼出處往上翻:
① renamTo (File dest):對文件進行重命名,它的使用分一下三種場景:
場景一:相同路徑下,只對文件進行重命名操作,命名成功後返回true:
File oldName = new File("E:\\hello\\test\\1.txt");
File newName = new File("E:\\hello\\test\\2.txt");
System.out.println(oldName.renameTo(newName));//命名成功返回true
場景二:將文件從一個路徑移動到另一個路徑下,並且對移動的文件進行重命名【文件移動重命名】
說明:將E:\hello\test\1.txt下的 1.txt 移動到E:\hello1\test1\路徑下,並重名命名爲2.txt .
其中 E:\hello1\test1必須要存在,否則返回false 。
File oldName = new File("E:\\hello\\test\\1.txt");
File newName = new File("E:\\hello1\\test1\\2.txt");
System.out.println(oldName.renameTo(newName));//移動且命名成功返回true
第三種場景:修改文件夾的名稱,文件夾裏面沒有文件的時候修改成功(注意不是修改文件名了,是文件夾名)!
說明:修改文件夾名稱,這個目錄必須存在 E:\hello\dufy。
其中如果 E:\hello\dufy 這個目錄不爲空,返回false。
File oldNamed = new File("E:\\hello\\dufy");
File newNamed = new File("E:\\hello\\dufy_fly");
System.out.println(oldNamed.renameTo(newNamed)); //true
② 陸續補充...