认识Java中关于文件的两个类File和FileSystem及常用方法总结

认识Java中关于文件的两个类File和FileSystem及常用方法总结

2023年6月25日发(作者:)

认识Java中关于⽂件的两个类File和FileSystem及常⽤⽅法总结认识Java中关于⽂件的两个类FileSystem和FIle类,两篇⽂章很长,建议精读的⽤⿏标滚轮滑动,泛读或看⽅法使⽤的直接单击拖动到最底部⽅法总结部分。

package ;import ;/** * 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 * true if the file was created and false 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 true 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 null. */ public abstract String[] list(File f); /** * Create a new directory denoted by the given abstract pathname, * returning true 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 true 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 true 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 true 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); 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 = perty(prop); if (val == null) return defaultVal; if (IgnoreCase("true")) { return true; } else { return false; } } static { useCanonCaches = getBooleanProperty("onCaches", useCanonCaches); useCanonPrefixCache = getBooleanProperty("onPrefixCache", useCanonPrefixCache); }} File类如下:package ;import ;import ;import medURLException;import taxException;import ;import ist;import Controller;import ;import stems;import pertyAction;/** * An abstract representation of file and directory pathnames. * ...... */public class File implements Serializable, Comparable{ /** * The FileSystem object representing the platform's local file system. */ private static final FileSystem fs = eSystem(); /** /** * 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 = (f('u0000') < 0) ? D : D; } return status == D; } /** * 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 tor. On UNIX systems the value of this * field is '/'; on Microsoft Windows systems it is ''. * * @see #getProperty() */ public static final char separatorChar = arator(); /** * The system-dependent default name-separator character, represented as a * string for convenience. This string contains a single character, namely * {@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 tor. This character is used to * separate filenames in a sequence of files given as a path list. * On UNIX systems, this character is ':'; on Microsoft Windows systems it * is ';'. * * @see #getProperty() */ public static final char pathSeparatorChar = hSeparator(); /** * The system-dependent path-separator character, represented as a string * for convenience. This string contains a single character, namely * {@link #pathSeparatorChar}. */ public static final String pathSeparator = "" + pathSeparatorChar; /* -- Constructors -- */ /** * Internal constructor for already-normalized pathname strings. */ private File(String pathname, int prefixLength) { = pathname; Length = 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 != null; assert (!("")); = e(, child); Length = Length; } /** * Creates a new 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 pathname argument is null */ public File(String pathname) { if (pathname == null) { throw new NullPointerException(); } = ize(pathname); Length = Length(); } /* 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 aultParent 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 File instance from a parent pathname string * and a child pathname string. * *

If parent is null then the new * File instance is created as if by invoking the * single-argument File constructor on the given * child pathname string. * *

Otherwise the parent pathname string is taken to denote * a directory, and the child pathname string is taken to * denote either a directory or a file. If the child pathname * string is absolute then it is converted into a relative pathname in a * system-dependent way. If parent is the empty string then * the new File instance is created by converting * child 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 child is null */ public File(String parent, String child) { if (child == null) { throw new NullPointerException(); } if (parent != null && !y()) { = e(ize(parent), ize(child)); } else { = ize(child); } Length = Length(); } /** * Creates a new File instance from a parent abstract * pathname and a child pathname string. * *

If parent is null then the new * File instance is created as if by invoking the * single-argument File constructor on the given * child pathname string. * *

Otherwise the parent abstract pathname is taken to * denote a directory, and the child pathname string is taken * to denote either a directory or a file. If the child * pathname string is absolute then it is converted into a relative * pathname in a system-dependent way. If parent is the empty * abstract pathname then the new File instance is created by * converting child 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 child is null */ public File(File parent, String child) { if (child == null) { throw new NullPointerException(); } if (parent != null) { if (("")) { = e(aultParent(), ize(child)); } else { = e(, ize(child)); } } else { = ize(child); } Length = Length(); } /** * Creates a new File instance by converting the given * file: URI into an abstract pathname. * *

The exact form of a file: URI is system-dependent, hence * the transformation performed by this constructor is also * system-dependent. * *

For a given abstract pathname f it is guaranteed that * *

* new File( f.{@link #toURI() toURI}()).equals( f.{@link #getAbsoluteFile() getAbsoluteFile}()) *
* * 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 file: 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 * "file", a non-empty path component, and undefined * authority, query, and fragment components * * @throws NullPointerException * If uri is null * * @throws IllegalArgumentException * If the preconditions on the parameter do not hold * * @see #toURI() * @see * @since 1.4 */ public File(URI uri) { // Check our many preconditions if (!lute()) throw new IllegalArgumentException("URI is not absolute"); if (ue()) throw new IllegalArgumentException("URI is not hierarchical"); String scheme = eme(); if ((scheme == null) || !IgnoreCase("file")) throw new IllegalArgumentException("URI scheme is not "file""); if (hority() != null) throw new IllegalArgumentException("URI has an authority component"); if (gment() != null) throw new IllegalArgumentException("URI has a fragment component"); if (ry() != null) throw new IllegalArgumentException("URI has a query component"); String p = h(); if (("")) throw new IllegalArgumentException("URI path component is empty"); // Okay, now initialize p = IPath(p); if (torChar != '/') p = e('/', torChar); = ize(p); Length = Length(); } /* -- 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 = dexOf(separatorChar); if (index < prefixLength) return ing(prefixLength); return ing(index + 1); } /** * Returns the pathname string of this abstract pathname's parent, or * null if this pathname does not name a parent directory. * *

The parent 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 null if this pathname * does not name a parent */ public String getParent() { int index = dexOf(separatorChar); if (index < prefixLength) { if ((prefixLength > 0) && (() > prefixLength)) return ing(0, prefixLength); return null; } return ing(0, index); } /** * Returns the abstract pathname of this abstract pathname's parent, * or null if this pathname does not name a parent * directory. * *

The parent 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 null if this pathname * does not name a parent * * @since 1.2 */ public File getParentFile() { String p = ent(); if (p == null) return null; return new File(p, Length); } /** * 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 true if this abstract pathname is absolute, * false otherwise */ public boolean isAbsolute() { return lute(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 /}. * *

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 #isAbsolute() */ public String getAbsolutePath() { return e(this); } /** * Returns the absolute form of this abstract pathname. Equivalent to * new File(this.{@link #getAbsolutePath}). * */ public File getAbsoluteFile() { String absPath = getAbsolutePath(); return new File(absPath, Length(absPath)); } /** * Returns the canonical pathname string of this abstract pathname. *...... */ public String getCanonicalPath() throws IOException { if (isInvalid()) { throw new IOException("Invalid file path"); } return calize(e(this)); } /** * Returns the canonical form of this abstract pathname. Equivalent to * new File(this.{@link #getCanonicalPath}). * */ public File getCanonicalFile() throws IOException { String canonPath = getCanonicalPath(); return new File(canonPath, Length(canonPath)); } private static String slashify(String path, boolean isDirectory) { String p = path; if (torChar != '/') p = e(torChar, '/'); if (!With("/")) p = "/" + p; if (!th("/") && isDirectory) p = p + "/"; return p; } /** * Converts this abstract pathname into a file: 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 file: URI that represents this abstract pathname. * *...... */ public URI toURI() { try { File f = getAbsoluteFile(); String sp = slashify(h(), ctory()); if (With("//")) 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 true if and only if the file specified by this * abstract pathname exists and can be read by the * application; false otherwise * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkRead()} * method denies read access to the file */ public boolean canRead() { SecurityManager security = urityManager(); if (security != null) { ead(path); } if (isInvalid()) { return false; } return ccess(this, _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 true if and only if the file system actually * contains a file denoted by this abstract pathname and * the application is allowed to write to the file; * false otherwise. * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkWrite()} * method denies write access to the file */ public boolean canWrite() { SecurityManager security = urityManager(); if (security != null) { rite(path); } if (isInvalid()) { return false; } return ccess(this, _WRITE); } /** * Tests whether the file or directory denoted by this abstract pathname * exists. * * @return true if and only if the file or directory denoted * by this abstract pathname exists; false otherwise * * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkRead()} * method denies read access to the file or directory */ public boolean exists() { SecurityManager security = urityManager(); if (security != null) { ead(path); } if (isInvalid()) { return false; } return ccess(this, _OK); } /** * Tests whether the file denoted by this abstract pathname is a * directory. * *

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 * #readAttributes(Path,Class,LinkOption[]) * tributes} method may be used. * * @return true if and only if the file denoted by this * abstract pathname exists and is a directory; * false otherwise * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkRead()} * method denies read access to the file */ public boolean isDirectory() { SecurityManager security = urityManager(); if (security != null) { ead(path); } if (isInvalid()) { return false; } return ((leanAttributes(this) & _DIRECTORY) != 0); } /** * Tests whether the file denoted by this abstract pathname is a normal * file. A file is normal 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. * *

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 * #readAttributes(Path,Class,LinkOption[]) * tributes} method may be used. * * @return true if and only if the file denoted by this * abstract pathname exists and is a normal file; * false otherwise * * @throws SecurityException * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkRead()} * method denies read access to the file */ public boolean isFile() { SecurityManager security = urityManager(); if (security != null) { ead(path); } if (isInvalid()) { return false; } return ((leanAttributes(this) & _REGULAR) != 0); } /** * Tests whether the file named by this abstract pathname is a hidden * file. The exact definition of hidden is system-dependent. On * UNIX systems, a file is considered to be hidden if its name begins with * a period character ('.'). On Microsoft Windows systems, a file is * considered to be hidden if it has been marked as such in the filesystem. * * @return true 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 {@link * tyManager#checkRead()} * method denies read access to the file * * @since 1.2 */ public boolean isHidden() { SecurityManager security = urityManager(); if (security != null) { ead(path); } if (isInvalid()) { return false; } return ((leanAttributes(this) & _HIDDEN) != 0); } /** * Returns the time that the file denoted by this abstract pathname was * last modified. * *

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 * #readAttributes(Path,Class,LinkOption[]) * tributes} method may be used. * * @return A long value representing the time the file was * last modified, measured in milliseconds since the epoch * (00:00:00 GMT, January 1, 1970), or 0L if the * file does not exist or if an I/O error occurs * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkRead()} * method denies read access to the file */ */ public long lastModified() { SecurityManager security = urityManager(); if (security != null) { ead(path); } if (isInvalid()) { return 0L; } return tModifiedTime(this); } /** * Returns the length of the file denoted by this abstract pathname. * The return value is unspecified if this pathname denotes a directory. * *

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 * #readAttributes(Path,Class,LinkOption[]) * tributes} method may be used. * * @return The length, in bytes, of the file denoted by this abstract * pathname, or 0L if the file does not exist. Some * operating systems may return 0L for pathnames * denoting system-dependent entities such as devices or pipes. * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkRead()} * method denies read access to the file */ public long length() { SecurityManager security = urityManager(); if (security != null) { ead(path); } if (isInvalid()) { return 0L; } return gth(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. *

* Note: this method should not be used for file-locking, as * the resulting protocol cannot be made to work reliably. The * {@link ck FileLock} * facility should be used instead. * * @return true if the named file does not exist and was * successfully created; false if the named file * already exists * * @throws IOException * If an I/O error occurred * * @throws SecurityException * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkWrite()} * method denies write access to the file * * @since 1.2 */ public boolean createNewFile() throws IOException { SecurityManager security = urityManager(); if (security != null) rite(path); if (isInvalid()) { throw new IOException("Invalid file path"); } return FileExclusively(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. * *

Note that the {@link } class defines the {@link * #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 true if and only if the file or directory is * successfully deleted; false otherwise * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkDelete} method denies * delete access to the file */ public boolean delete() { SecurityManager security = urityManager(); if (security != null) { elete(path); } if (isInvalid()) { return false; } return (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 = urityManager(); if (security != null) { elete(path); } if (isInvalid()) { return; } (path); } /** * Returns an array of strings naming the files and directories in the * directory denoted by this abstract pathname. * *

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. * *

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. * *

Note that the {@link } class defines the {@link * #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 = urityManager(); if (security != null) { ead(path); } if (isInvalid()) { return null; } return (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 (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 #newDirectoryStream(Path,String) */ public String[] list(FilenameFilter filter) { String names[] = list(); if ((names == null) || (filter == null)) { return names; } List v = new ArrayList<>(); for (int i = 0 ; i < ; i++) { if ((this, names[i])) { (names[i]); } } return y(new String[()]); }

public File[] listFiles() { String[] ss = list(); if (ss == null) return null; int n = ; 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 files = new ArrayList<>(); for (String s : ss) if ((filter == null) || (this, s)) (new File(s, this)); return y(new File[()]); }

public File[] listFiles(FileFilter filter) { String ss[] = list(); if (ss == null) return null; ArrayList files = new ArrayList<>(); for (String s : ss) { File f = new File(s, this); if ((filter == null) || (f)) (f); } return y(new File[()]); } /** * Creates the directory named by this abstract pathname. * * @return true if and only if the directory was * created; false otherwise * * @throws SecurityException * If a security manager exists and its {@link * If a security manager exists and its {@link * tyManager#checkWrite()} * method does not permit the named directory to be created */ public boolean mkdir() { SecurityManager security = urityManager(); if (security != null) { rite(path); } if (isInvalid()) { return false; } return Directory(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 true if and only if the directory was created, * along with all necessary parent directories; false * otherwise * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkRead()} * method does not permit verification of the existence of the * named directory and all necessary parent directories; or if * the {@link * tyManager#checkWrite()} * 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 = entFile(); return (parent != null && (() || ()) && ()); } /** * Renames the file denoted by this abstract pathname. * *

Many failures are possible. Some of the more likely failures include: *

    *
  • Write permission is required on the directories containing both the source and * destination paths. *
  • Search permission is required for all parents of both paths. *
  • 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. *
* * *

The return value should always be checked to make sure * that the rename operation was successful. * *

Note that the {@link } class defines the {@link * #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 true if and only if the renaming succeeded; * false otherwise * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkWrite()} * method denies write access to either the old or new pathnames * * @throws NullPointerException * If parameter dest is null */ public boolean renameTo(File dest) { SecurityManager security = urityManager(); if (security != null) { rite(path); rite(); } if (dest == null) { throw new NullPointerException(); } if (lid() || lid()) { return false; } return (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 = urityManager(); if (security != null) { rite(path); } if (isInvalid()) { return false; } return tModifiedTime(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 = urityManager(); if (security != null) { if (security != null) { rite(path); } if (isInvalid()) { return false; } return dOnly(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 = urityManager(); if (security != null) { rite(path); } if (isInvalid()) { return false; } return mission(this, _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. * *

The {@link } 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 = urityManager(); if (security != null) { rite(path); } if (isInvalid()) { return false; } return mission(this, _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. * 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. * *

The {@link } 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 = urityManager(); if (security != null) { rite(path); } if (isInvalid()) { return false; } return mission(this, _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 true if and only if the abstract pathname exists * and the application is allowed to execute the file * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkExec()} * method denies execute access to the file * * @since 1.6 */ public boolean canExecute() { SecurityManager security = urityManager(); if (security != null) { xec(path); } if (isInvalid()) { return false; } return ccess(this, _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 ots(); } /* -- Disk usage -- */ /** * Returns the size of the partition named by this * abstract pathname. *...... */ public long getTotalSpace() { SecurityManager sm = urityManager(); if (sm != null) { ermission(new RuntimePermission("getFileSystemAttributes")); ead(path); } if (isInvalid()) { return 0L; } return ce(this, _TOTAL); } /** * Returns the number of unallocated bytes in the partition named by this abstract path name. *...... */ public long getFreeSpace() { SecurityManager sm = urityManager(); if (sm != null) { ermission(new RuntimePermission("getFileSystemAttributes")); ead(path); } if (isInvalid()) { return 0L; } return ce(this, _FREE); } /** * Returns the number of bytes available to this virtual machine on the * partition named 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 = urityManager(); if (sm != null) { ermission(new RuntimePermission("getFileSystemAttributes")); ead(path); } if (isInvalid()) { return 0L; } } return ce(this, _USABLE); } /* -- Temporary files -- */ private static class TempDirectory { private TempDirectory() { } // Android-changed: Don't cache value // temporary directory location // private static final File tmpdir = new File(AccessController // .doPrivileged(new GetPropertyAction(""))); // static File location() { // return tmpdir; // } // file name generation static File generateFile(String prefix, String suffix, File dir) throws IOException { // Android-changed: Use IntInternal. This (pseudo) random number // is initialized post-fork long n = LongInternal(); if (n == _VALUE) { n = 0; // corner case } else { n = (n); } // Android-changed: Reject invalid file prefixes // Use only the file name from the supplied prefix //prefix = (new File(prefix)).getName(); String name = prefix + ng(n) + suffix; File f = new File(dir, name); if (!(e()) || lid()) { if (urityManager() != null) throw new IOException("Unable to create temporary file"); else throw new IOException("Unable to create temporary file, " + f); } return f; } } /** *

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 null, in which case the * suffix ".tmp" will be used * * @param directory The directory in which the file is to be created, or * null if the default temporary-file * directory is to be used * * @return An abstract pathname denoting a newly-created empty file * * * @throws IllegalArgumentException * If the prefix argument contains fewer than three * characters * * @throws IOException If a file could not be created * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkWrite()} * 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 (() < 3) throw new IllegalArgumentException("Prefix string too short"); if (suffix == null) suffix = ".tmp"; File tmpdir = (directory != null) ? directory : new File(perty("", ".")); //SecurityManager sm = urityManager(); File f; do { f = teFile(prefix, suffix, tmpdir); // Android change: sm is always null on android // if (sm != null) { // try { // rite(h()); // } catch (SecurityException se) { // // don't reveal temporary directory location // if (directory == null) // throw new SecurityException("Unable to create temporary file"); // throw se; // } // } } while ((leanAttributes(f) & _EXISTS) != 0); if (!FileExclusively(h())) 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 {@link #createTempFile(, * , ) * createTempFile(prefix, suffix, null)}. * *

The {@link * #createTempFile(String,String,tribute[]) * TempFile} 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 * name; must be at least three characters long * * @param suffix The suffix string to be used in generating the file's * name; may be null, in which case the * suffix ".tmp" will be used * * @return An abstract pathname denoting a newly-created empty file * * @throws IllegalArgumentException * If the prefix argument contains fewer than three * characters * * @throws IOException If a file could not be created * * @throws SecurityException * If a security manager exists and its {@link * tyManager#checkWrite()} * method does not allow a file to be created * * @since 1.2 * @see #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 e(this, pathname); } /** * Tests this abstract pathname for equality with the given object. * Returns true if and only if the argument is not * null 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 true if and only if the objects are the same; * false otherwise */ public boolean equals(Object obj) { 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 or of the hash code * of its pathname string and the decimal value * 1234321. On Microsoft Windows systems, the hash * code is equal to the exclusive or of the hash code of * its pathname string converted to lower case and the decimal * value 1234321. Locale is not taken into account on * lowercasing the pathname string. * * @return A hash code for this abstract pathname */ public int hashCode() { return de(this); } /** * Returns the pathname string of this abstract pathname. This is just the * string returned by the {@link #getPath} 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. *

* @serialData Default fields followed by separator character. */ private synchronized void writeObject(OutputStream s) throws IOException { tWriteObject(); har(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(InputStream s) throws IOException, ClassNotFoundException { ld fields = elds(); String pathField = (String)("path", null); char sep = ar(); // read the previous separator char if (sep != separatorChar) pathField = e(sep, separatorChar); String path = ize(pathField); ect(this, PATH_OFFSET, path); Volatile(this, PREFIX_LENGTH_OFFSET, Length(path)); Volatile(this, PREFIX_LENGTH_OFFSET, Length(path)); } private static final long PATH_OFFSET; private static final long PREFIX_LENGTH_OFFSET; private static final UNSAFE; static { try { unsafe = afe(); PATH_OFFSET = FieldOffset( laredField("path")); PREFIX_LENGTH_OFFSET = FieldOffset( laredField("prefixLength")); UNSAFE = unsafe; } catch (ReflectiveOperationException e) { throw new Error(e); } } /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = 381567L; // -- Integration with -- private volatile transient Path filePath; /** * Returns a {@link Path } object constructed from the * this abstract path. The resulting {@code Path} is associated with the * {@link stems#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 = ault().getPath(path); filePath = result; } } } return result; }}⽅法总结部分下⾯总结的⽅法均来⾃上⾯两个类,想看源码出处往上翻:① renamTo (File dest):对⽂件进⾏重命名,它的使⽤分⼀下三种场景: 场景⼀:相同路径下,只对⽂件进⾏重命名操作,命名成功后返回true:

File oldName = new File("E:"); File newName = new File("E:"); n(To(newName));//命名成功返回true场景⼆:将⽂件从⼀个路径移动到另⼀个路径下,并且对移动的⽂件进⾏重命名【⽂件移动重命名】说明:将E:下的 移动到E:hello1test1路径下,并重名命名为 .其中 E:hello1test1必须要存在,否则返回false 。 File oldName = new File("E:"); File newName = new File("E:"); n(To(newName));//移动且命名成功返回true第三种场景:修改⽂件夹的名称,⽂件夹⾥⾯没有⽂件的时候修改成功(注意不是修改⽂件名了,是⽂件夹名)!说明:修改⽂件夹名称,这个⽬录必须存在 E:hellodufy。其中如果 E:hellodufy 这个⽬录不为空,返回false。 File oldNamed = new File("E:hellodufy"); File newNamed = new File("E:hellodufy_fly"); n(To(newNamed)); //true② 陆续补充...

发布者:admin,转转请注明出处:http://www.yc00.com/web/1687679175a30919.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信