       1 /*
       2  * Copyright (c) 1994, 2020, Oracle and/or its affiliates. All rights reserved.
       3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       4  *
       5  * This code is free software; you can redistribute it and/or modify it
       6  * under the terms of the GNU General Public License version 2 only, as
       7  * published by the Free Software Foundation.  Oracle designates this
       8  * particular file as subject to the "Classpath" exception as provided
       9  * by Oracle in the LICENSE file that accompanied this code.
      10  *
      11  * This code is distributed in the hope that it will be useful, but WITHOUT
      12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
      13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
      14  * version 2 for more details (a copy is included in the LICENSE file that
      15  * accompanied this code).
      16  *
      17  * You should have received a copy of the GNU General Public License version
      18  * 2 along with this work; if not, write to the Free Software Foundation,
      19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
      20  *
      21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
      22  * or visit www.oracle.com if you need additional information or have any
      23  * questions.
      24  */
      25
      26 package java.io;
      27
      28 import java.net.URI;
      29 import java.net.URL;
      30 import java.net.MalformedURLException;
      31 import java.net.URISyntaxException;
      32 import java.nio.file.FileStore;
      33 import java.nio.file.FileSystems;
      34 import java.nio.file.Path;
      35 import java.security.SecureRandom;
      36 import java.util.ArrayList;
      37 import java.util.List;
      38 import sun.security.action.GetPropertyAction;
      39
      40 /**
      41  * An abstract representation of file and directory pathnames.
      42  *
      43  * <p> User interfaces and operating systems use system-dependent <em>pathname
      44  * strings</em> to name files and directories.  This class presents an
      45  * abstract, system-independent view of hierarchical pathnames.  An
      46  * <em>abstract pathname</em> has two components:
      47  *
      48  * <ol>
      49  * <li> An optional system-dependent <em>prefix</em> string,
      50  *      such as a disk-drive specifier, {@code "/"}&nbsp;for the UNIX root
      51  *      directory, or {@code "\\\\"}&nbsp;for a Microsoft Windows UNC pathname, and
      52  * <li> A sequence of zero or more string <em>names</em>.
      53  * </ol>
      54  *
      55  * The first name in an abstract pathname may be a directory name or, in the
      56  * case of Microsoft Windows UNC pathnames, a hostname.  Each subsequent name
      57  * in an abstract pathname denotes a directory; the last name may denote
      58  * either a directory or a file.  The <em>empty</em> abstract pathname has no
      59  * prefix and an empty name sequence.
      60  *
      61  * <p> The conversion of a pathname string to or from an abstract pathname is
      62  * inherently system-dependent.  When an abstract pathname is converted into a
      63  * pathname string, each name is separated from the next by a single copy of
      64  * the default <em>separator character</em>.  The default name-separator
      65  * character is defined by the system property {@code file.separator}, and
      66  * is made available in the public static fields {@link
      67  * #separator} and {@link #separatorChar} of this class.
      68  * When a pathname string is converted into an abstract pathname, the names
      69  * within it may be separated by the default name-separator character or by any
      70  * other name-separator character that is supported by the underlying system.
      71  *
      72  * <p> A pathname, whether abstract or in string form, may be either
      73  * <em>absolute</em> or <em>relative</em>.  An absolute pathname is complete in
      74  * that no other information is required in order to locate the file that it
      75  * denotes.  A relative pathname, in contrast, must be interpreted in terms of
      76  * information taken from some other pathname.  By default the classes in the
      77  * {@code java.io} package always resolve relative pathnames against the
      78  * current user directory.  This directory is named by the system property
      79  * {@code user.dir}, and is typically the directory in which the Java
      80  * virtual machine was invoked.
      81  *
      82  * <p> The <em>parent</em> of an abstract pathname may be obtained by invoking
      83  * the {@link #getParent} method of this class and consists of the pathname's
      84  * prefix and each name in the pathname's name sequence except for the last.
      85  * Each directory's absolute pathname is an ancestor of any {@code File}
      86  * object with an absolute abstract pathname which begins with the directory's
      87  * absolute pathname.  For example, the directory denoted by the abstract
      88  * pathname {@code "/usr"} is an ancestor of the directory denoted by the
      89  * pathname {@code "/usr/local/bin"}.
      90  *
      91  * <p> The prefix concept is used to handle root directories on UNIX platforms,
      92  * and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms,
      93  * as follows:
      94  *
      95  * <ul>
      96  *
      97  * <li> For UNIX platforms, the prefix of an absolute pathname is always
      98  * {@code "/"}.  Relative pathnames have no prefix.  The abstract pathname
      99  * denoting the root directory has the prefix {@code "/"} and an empty
     100  * name sequence.
     101  *
     102  * <li> For Microsoft Windows platforms, the prefix of a pathname that contains a drive
     103  * specifier consists of the drive letter followed by {@code ":"} and
     104  * possibly followed by {@code "\\"} if the pathname is absolute.  The
     105  * prefix of a UNC pathname is {@code "\\\\"}; the hostname and the share
     106  * name are the first two names in the name sequence.  A relative pathname that
     107  * does not specify a drive has no prefix.
     108  *
     109  * </ul>
     110  *
     111  * <p> Instances of this class may or may not denote an actual file-system
     112  * object such as a file or a directory.  If it does denote such an object
     113  * then that object resides in a <i>partition</i>.  A partition is an
     114  * operating system-specific portion of storage for a file system.  A single
     115  * storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may
     116  * contain multiple partitions.  The object, if any, will reside on the
     117  * partition <a id="partName">named</a> by some ancestor of the absolute
     118  * form of this pathname.
     119  *
     120  * <p> A file system may implement restrictions to certain operations on the
     121  * actual file-system object, such as reading, writing, and executing.  These
     122  * restrictions are collectively known as <i>access permissions</i>.  The file
     123  * system may have multiple sets of access permissions on a single object.
     124  * For example, one set may apply to the object's <i>owner</i>, and another
     125  * may apply to all other users.  The access permissions on an object may
     126  * cause some methods in this class to fail.
     127  *
     128  * <p> Instances of the {@code File} class are immutable; that is, once
     129  * created, the abstract pathname represented by a {@code File} object
     130  * will never change.
     131  *
     132  * <h2>Interoperability with {@code java.nio.file} package</h2>
     133  *
     134  * <p> The <a href="../../java/nio/file/package-summary.html">{@code java.nio.file}</a>
     135  * package defines interfaces and classes for the Java virtual machine to access
     136  * files, file attributes, and file systems. This API may be used to overcome
     137  * many of the limitations of the {@code java.io.File} class.
     138  * The {@link #toPath toPath} method may be used to obtain a {@link
     139  * Path} that uses the abstract path represented by a {@code File} object to
     140  * locate a file. The resulting {@code Path} may be used with the {@link
     141  * java.nio.file.Files} class to provide more efficient and extensive access to
     142  * additional file operations, file attributes, and I/O exceptions to help
     143  * diagnose errors when an operation on a file fails.
     144  *
     145  * @author  unascribed
     146  * @since   1.0
     147  */
     148
     149 public class File
     150     implements Serializable, Comparable<File>
     151 {
     152
     153     /**
     154      * The FileSystem object representing the platform's local file system.
     155      */
     156     private static final FileSystem fs = DefaultFileSystem.getFileSystem();
     157
     158     /**
     159      * This abstract pathname's normalized pathname string. A normalized
     160      * pathname string uses the default name-separator character and does not
     161      * contain any duplicate or redundant separators.
     162      *
     163      * @serial
     164      */
     165     private final String path;
     166
     167     /**
     168      * Enum type that indicates the status of a file path.
     169      */
     170     private static enum PathStatus { INVALID, CHECKED };
     171
     172     /**
     173      * The flag indicating whether the file path is invalid.
     174      */
     175     private transient PathStatus status = null;
     176
     177     /**
     178      * Check if the file has an invalid path. Currently, the inspection of
     179      * a file path is very limited, and it only covers Nul character check.
     180      * Returning true means the path is definitely invalid/garbage. But
     181      * returning false does not guarantee that the path is valid.
     182      *
     183      * @return true if the file path is invalid.
     184      */
     185     final boolean isInvalid() {
     186         PathStatus s = status;
     187         if (s == null) {
     188             s = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED
     189                                                   : PathStatus.INVALID;
     190             status = s;
     191         }
     192         return s == PathStatus.INVALID;
     193     }
     194
     195     /**
     196      * The length of this abstract pathname's prefix, or zero if it has no
     197      * prefix.
     198      */
     199     private final transient int prefixLength;
     200
     201     /**
     202      * Returns the length of this abstract pathname's prefix.
     203      * For use by FileSystem classes.
     204      */
     205     int getPrefixLength() {
     206         return prefixLength;
     207     }
     208
     209     /**
     210      * The system-dependent default name-separator character.  This field is
     211      * initialized to contain the first character of the value of the system
     212      * property {@code file.separator}.  On UNIX systems the value of this
     213      * field is {@code '/'}; on Microsoft Windows systems it is {@code '\\'}.
     214      *
     215      * @see     java.lang.System#getProperty(java.lang.String)
     216      */
     217     public static final char separatorChar = fs.getSeparator();
     218
     219     /**
     220      * The system-dependent default name-separator character, represented as a
     221      * string for convenience.  This string contains a single character, namely
     222      * {@link #separatorChar}.
     223      */
     224     public static final String separator = "" + separatorChar;
     225
     226     /**
     227      * The system-dependent path-separator character.  This field is
     228      * initialized to contain the first character of the value of the system
     229      * property {@code path.separator}.  This character is used to
     230      * separate filenames in a sequence of files given as a <em>path list</em>.
     231      * On UNIX systems, this character is {@code ':'}; on Microsoft Windows systems it
     232      * is {@code ';'}.
     233      *
     234      * @see     java.lang.System#getProperty(java.lang.String)
     235      */
     236     public static final char pathSeparatorChar = fs.getPathSeparator();
     237
     238     /**
     239      * The system-dependent path-separator character, represented as a string
     240      * for convenience.  This string contains a single character, namely
     241      * {@link #pathSeparatorChar}.
     242      */
     243     public static final String pathSeparator = "" + pathSeparatorChar;
     244
     245
     246     /* -- Constructors -- */
     247
     248     /**
     249      * Internal constructor for already-normalized pathname strings.
     250      */
     251     private File(String pathname, int prefixLength) {
     252         this.path = pathname;
     253         this.prefixLength = prefixLength;
     254     }
     255
     256     /**
     257      * Internal constructor for already-normalized pathname strings.
     258      * The parameter order is used to disambiguate this method from the
     259      * public(File, String) constructor.
     260      */
     261     private File(String child, File parent) {
     262         assert parent.path != null;
     263         assert (!parent.path.isEmpty());
     264         this.path = fs.resolve(parent.path, child);
     265         this.prefixLength = parent.prefixLength;
     266     }
     267
     268     /**
     269      * Creates a new {@code File} instance by converting the given
     270      * pathname string into an abstract pathname.  If the given string is
     271      * the empty string, then the result is the empty abstract pathname.
     272      *
     273      * @param   pathname  A pathname string
     274      * @throws  NullPointerException
     275      *          If the {@code pathname} argument is {@code null}
     276      */
     277     public File(String pathname) {
     278         if (pathname == null) {
     279             throw new NullPointerException();
     280         }
     281         this.path = fs.normalize(pathname);
     282         this.prefixLength = fs.prefixLength(this.path);
     283     }
     284
     285     /* Note: The two-argument File constructors do not interpret an empty
     286        parent abstract pathname as the current user directory.  An empty parent
     287        instead causes the child to be resolved against the system-dependent
     288        directory defined by the FileSystem.getDefaultParent method.  On Unix
     289        this default is "/", while on Microsoft Windows it is "\\".  This is required for
     290        compatibility with the original behavior of this class. */
     291
     292     /**
     293      * Creates a new {@code File} instance from a parent pathname string
     294      * and a child pathname string.
     295      *
     296      * <p> If {@code parent} is {@code null} then the new
     297      * {@code File} instance is created as if by invoking the
     298      * single-argument {@code File} constructor on the given
     299      * {@code child} pathname string.
     300      *
     301      * <p> Otherwise the {@code parent} pathname string is taken to denote
     302      * a directory, and the {@code child} pathname string is taken to
     303      * denote either a directory or a file.  If the {@code child} pathname
     304      * string is absolute then it is converted into a relative pathname in a
     305      * system-dependent way.  If {@code parent} is the empty string then
     306      * the new {@code File} instance is created by converting
     307      * {@code child} into an abstract pathname and resolving the result
     308      * against a system-dependent default directory.  Otherwise each pathname
     309      * string is converted into an abstract pathname and the child abstract
     310      * pathname is resolved against the parent.
     311      *
     312      * @param   parent  The parent pathname string
     313      * @param   child   The child pathname string
     314      * @throws  NullPointerException
     315      *          If {@code child} is {@code null}
     316      */
     317     public File(String parent, String child) {
     318         if (child == null) {
     319             throw new NullPointerException();
     320         }
     321         if (parent != null) {
     322             if (parent.isEmpty()) {
     323                 this.path = fs.resolve(fs.getDefaultParent(),
     324                                        fs.normalize(child));
     325             } else {
     326                 this.path = fs.resolve(fs.normalize(parent),
     327                                        fs.normalize(child));
     328             }
     329         } else {
     330             this.path = fs.normalize(child);
     331         }
     332         this.prefixLength = fs.prefixLength(this.path);
     333     }
     334
     335     /**
     336      * Creates a new {@code File} instance from a parent abstract
     337      * pathname and a child pathname string.
     338      *
     339      * <p> If {@code parent} is {@code null} then the new
     340      * {@code File} instance is created as if by invoking the
     341      * single-argument {@code File} constructor on the given
     342      * {@code child} pathname string.
     343      *
     344      * <p> Otherwise the {@code parent} abstract pathname is taken to
     345      * denote a directory, and the {@code child} pathname string is taken
     346      * to denote either a directory or a file.  If the {@code child}
     347      * pathname string is absolute then it is converted into a relative
     348      * pathname in a system-dependent way.  If {@code parent} is the empty
     349      * abstract pathname then the new {@code File} instance is created by
     350      * converting {@code child} into an abstract pathname and resolving
     351      * the result against a system-dependent default directory.  Otherwise each
     352      * pathname string is converted into an abstract pathname and the child
     353      * abstract pathname is resolved against the parent.
     354      *
     355      * @param   parent  The parent abstract pathname
     356      * @param   child   The child pathname string
     357      * @throws  NullPointerException
     358      *          If {@code child} is {@code null}
     359      */
     360     public File(File parent, String child) {
     361         if (child == null) {
     362             throw new NullPointerException();
     363         }
     364         if (parent != null) {
     365             if (parent.path.isEmpty()) {
     366                 this.path = fs.resolve(fs.getDefaultParent(),
     367                                        fs.normalize(child));
     368             } else {
     369                 this.path = fs.resolve(parent.path,
     370                                        fs.normalize(child));
     371             }
     372         } else {
     373             this.path = fs.normalize(child);
     374         }
     375         this.prefixLength = fs.prefixLength(this.path);
     376     }
     377
     378     /**
     379      * Creates a new {@code File} instance by converting the given
     380      * {@code file:} URI into an abstract pathname.
     381      *
     382      * <p> The exact form of a {@code file:} URI is system-dependent, hence
     383      * the transformation performed by this constructor is also
     384      * system-dependent.
     385      *
     386      * <p> For a given abstract pathname <i>f</i> it is guaranteed that
     387      *
     388      * <blockquote><code>
     389      * new File(</code><i>&nbsp;f</i><code>.{@link #toURI()
     390      * toURI}()).equals(</code><i>&nbsp;f</i><code>.{@link #getAbsoluteFile() getAbsoluteFile}())
     391      * </code></blockquote>
     392      *
     393      * so long as the original abstract pathname, the URI, and the new abstract
     394      * pathname are all created in (possibly different invocations of) the same
     395      * Java virtual machine.  This relationship typically does not hold,
     396      * however, when a {@code file:} URI that is created in a virtual machine
     397      * on one operating system is converted into an abstract pathname in a
     398      * virtual machine on a different operating system.
     399      *
     400      * @param  uri
     401      *         An absolute, hierarchical URI with a scheme equal to
     402      *         {@code "file"}, a non-empty path component, and undefined
     403      *         authority, query, and fragment components
     404      *
     405      * @throws  NullPointerException
     406      *          If {@code uri} is {@code null}
     407      *
     408      * @throws  IllegalArgumentException
     409      *          If the preconditions on the parameter do not hold
     410      *
     411      * @see #toURI()
     412      * @see java.net.URI
     413      * @since 1.4
     414      */
     415     public File(URI uri) {
     416
     417         // Check our many preconditions
     418         if (!uri.isAbsolute())
     419             throw new IllegalArgumentException("URI is not absolute");
     420         if (uri.isOpaque())
     421             throw new IllegalArgumentException("URI is not hierarchical");
     422         String scheme = uri.getScheme();
     423         if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
     424             throw new IllegalArgumentException("URI scheme is not \"file\"");
     425         if (uri.getRawAuthority() != null)
     426             throw new IllegalArgumentException("URI has an authority component");
     427         if (uri.getRawFragment() != null)
     428             throw new IllegalArgumentException("URI has a fragment component");
     429         if (uri.getRawQuery() != null)
     430             throw new IllegalArgumentException("URI has a query component");
     431         String p = uri.getPath();
     432         if (p.isEmpty())
     433             throw new IllegalArgumentException("URI path component is empty");
     434
     435         // Okay, now initialize
     436         p = fs.fromURIPath(p);
     437         if (File.separatorChar != '/')
     438             p = p.replace('/', File.separatorChar);
     439         this.path = fs.normalize(p);
     440         this.prefixLength = fs.prefixLength(this.path);
     441     }
     442
     443
     444     /* -- Path-component accessors -- */
     445
     446     /**
     447      * Returns the name of the file or directory denoted by this abstract
     448      * pathname.  This is just the last name in the pathname's name
     449      * sequence.  If the pathname's name sequence is empty, then the empty
     450      * string is returned.
     451      *
     452      * @return  The name of the file or directory denoted by this abstract
     453      *          pathname, or the empty string if this pathname's name sequence
     454      *          is empty
     455      */
     456     public String getName() {
     457         int index = path.lastIndexOf(separatorChar);
     458         if (index < prefixLength) return path.substring(prefixLength);
     459         return path.substring(index + 1);
     460     }
     461
     462     /**
     463      * Returns the pathname string of this abstract pathname's parent, or
     464      * {@code null} if this pathname does not name a parent directory.
     465      *
     466      * <p> The <em>parent</em> of an abstract pathname consists of the
     467      * pathname's prefix, if any, and each name in the pathname's name
     468      * sequence except for the last.  If the name sequence is empty then
     469      * the pathname does not name a parent directory.
     470      *
     471      * @return  The pathname string of the parent directory named by this
     472      *          abstract pathname, or {@code null} if this pathname
     473      *          does not name a parent
     474      */
     475     public String getParent() {
     476         int index = path.lastIndexOf(separatorChar);
     477         if (index < prefixLength) {
     478             if ((prefixLength > 0) && (path.length() > prefixLength))
     479                 return path.substring(0, prefixLength);
     480             return null;
     481         }
     482         return path.substring(0, index);
     483     }
     484
     485     /**
     486      * Returns the abstract pathname of this abstract pathname's parent,
     487      * or {@code null} if this pathname does not name a parent
     488      * directory.
     489      *
     490      * <p> The <em>parent</em> of an abstract pathname consists of the
     491      * pathname's prefix, if any, and each name in the pathname's name
     492      * sequence except for the last.  If the name sequence is empty then
     493      * the pathname does not name a parent directory.
     494      *
     495      * @return  The abstract pathname of the parent directory named by this
     496      *          abstract pathname, or {@code null} if this pathname
     497      *          does not name a parent
     498      *
     499      * @since 1.2
     500      */
     501     public File getParentFile() {
     502         String p = this.getParent();
     503         if (p == null) return null;
     504         return new File(p, this.prefixLength);
     505     }
     506
     507     /**
     508      * Converts this abstract pathname into a pathname string.  The resulting
     509      * string uses the {@link #separator default name-separator character} to
     510      * separate the names in the name sequence.
     511      *
     512      * @return  The string form of this abstract pathname
     513      */
     514     public String getPath() {
     515         return path;
     516     }
     517
     518
     519     /* -- Path operations -- */
     520
     521     /**
     522      * Tests whether this abstract pathname is absolute.  The definition of
     523      * absolute pathname is system dependent.  On UNIX systems, a pathname is
     524      * absolute if its prefix is {@code "/"}.  On Microsoft Windows systems, a
     525      * pathname is absolute if its prefix is a drive specifier followed by
     526      * {@code "\\"}, or if its prefix is {@code "\\\\"}.
     527      *
     528      * @return  {@code true} if this abstract pathname is absolute,
     529      *          {@code false} otherwise
     530      */
     531     public boolean isAbsolute() {
     532         return fs.isAbsolute(this);
     533     }
     534
     535     /**
     536      * Returns the absolute pathname string of this abstract pathname.
     537      *
     538      * <p> If this abstract pathname is already absolute, then the pathname
     539      * string is simply returned as if by the {@link #getPath}
     540      * method.  If this abstract pathname is the empty abstract pathname then
     541      * the pathname string of the current user directory, which is named by the
     542      * system property {@code user.dir}, is returned.  Otherwise this
     543      * pathname is resolved in a system-dependent way.  On UNIX systems, a
     544      * relative pathname is made absolute by resolving it against the current
     545      * user directory.  On Microsoft Windows systems, a relative pathname is made absolute
     546      * by resolving it against the current directory of the drive named by the
     547      * pathname, if any; if not, it is resolved against the current user
     548      * directory.
     549      *
     550      * @return  The absolute pathname string denoting the same file or
     551      *          directory as this abstract pathname
     552      *
     553      * @throws  SecurityException
     554      *          If a required system property value cannot be accessed.
     555      *
     556      * @see     java.io.File#isAbsolute()
     557      */
     558     public String getAbsolutePath() {
     559         return fs.resolve(this);
     560     }
     561
     562     /**
     563      * Returns the absolute form of this abstract pathname.  Equivalent to
     564      * <code>new&nbsp;File(this.{@link #getAbsolutePath})</code>.
     565      *
     566      * @return  The absolute abstract pathname denoting the same file or
     567      *          directory as this abstract pathname
     568      *
     569      * @throws  SecurityException
     570      *          If a required system property value cannot be accessed.
     571      *
     572      * @since 1.2
     573      */
     574     public File getAbsoluteFile() {
     575         String absPath = getAbsolutePath();
     576         return new File(absPath, fs.prefixLength(absPath));
     577     }
     578
     579     /**
     580      * Returns the canonical pathname string of this abstract pathname.
     581      *
     582      * <p> A canonical pathname is both absolute and unique.  The precise
     583      * definition of canonical form is system-dependent.  This method first
     584      * converts this pathname to absolute form if necessary, as if by invoking the
     585      * {@link #getAbsolutePath} method, and then maps it to its unique form in a
     586      * system-dependent way.  This typically involves removing redundant names
     587      * such as {@code "."} and {@code ".."} from the pathname, resolving
     588      * symbolic links (on UNIX platforms), and converting drive letters to a
     589      * standard case (on Microsoft Windows platforms).
     590      *
     591      * <p> Every pathname that denotes an existing file or directory has a
     592      * unique canonical form.  Every pathname that denotes a nonexistent file
     593      * or directory also has a unique canonical form.  The canonical form of
     594      * the pathname of a nonexistent file or directory may be different from
     595      * the canonical form of the same pathname after the file or directory is
     596      * created.  Similarly, the canonical form of the pathname of an existing
     597      * file or directory may be different from the canonical form of the same
     598      * pathname after the file or directory is deleted.
     599      *
     600      * @return  The canonical pathname string denoting the same file or
     601      *          directory as this abstract pathname
     602      *
     603      * @throws  IOException
     604      *          If an I/O error occurs, which is possible because the
     605      *          construction of the canonical pathname may require
     606      *          filesystem queries
     607      *
     608      * @throws  SecurityException
     609      *          If a required system property value cannot be accessed, or
     610      *          if a security manager exists and its {@link
     611      *          java.lang.SecurityManager#checkRead} method denies
     612      *          read access to the file
     613      *
     614      * @since   1.1
     615      * @see     Path#toRealPath
     616      */
     617     public String getCanonicalPath() throws IOException {
     618         if (isInvalid()) {
     619             throw new IOException("Invalid file path");
     620         }
     621         return fs.canonicalize(fs.resolve(this));
     622     }
     623
     624     /**
     625      * Returns the canonical form of this abstract pathname.  Equivalent to
     626      * <code>new&nbsp;File(this.{@link #getCanonicalPath})</code>.
     627      *
     628      * @return  The canonical pathname string denoting the same file or
     629      *          directory as this abstract pathname
     630      *
     631      * @throws  IOException
     632      *          If an I/O error occurs, which is possible because the
     633      *          construction of the canonical pathname may require
     634      *          filesystem queries
     635      *
     636      * @throws  SecurityException
     637      *          If a required system property value cannot be accessed, or
     638      *          if a security manager exists and its {@link
     639      *          java.lang.SecurityManager#checkRead} method denies
     640      *          read access to the file
     641      *
     642      * @since 1.2
     643      * @see     Path#toRealPath
     644      */
     645     public File getCanonicalFile() throws IOException {
     646         String canonPath = getCanonicalPath();
     647         return new File(canonPath, fs.prefixLength(canonPath));
     648     }
     649
     650     private static String slashify(String path, boolean isDirectory) {
     651         String p = path;
     652         if (File.separatorChar != '/')
     653             p = p.replace(File.separatorChar, '/');
     654         if (!p.startsWith("/"))
     655             p = "/" + p;
     656         if (!p.endsWith("/") && isDirectory)
     657             p = p + "/";
     658         return p;
     659     }
     660
     661     /**
     662      * Converts this abstract pathname into a {@code file:} URL.  The
     663      * exact form of the URL is system-dependent.  If it can be determined that
     664      * the file denoted by this abstract pathname is a directory, then the
     665      * resulting URL will end with a slash.
     666      *
     667      * @return  A URL object representing the equivalent file URL
     668      *
     669      * @throws  MalformedURLException
     670      *          If the path cannot be parsed as a URL
     671      *
     672      * @see     #toURI()
     673      * @see     java.net.URI
     674      * @see     java.net.URI#toURL()
     675      * @see     java.net.URL
     676      * @since   1.2
     677      *
     678      * @deprecated This method does not automatically escape characters that
     679      * are illegal in URLs.  It is recommended that new code convert an
     680      * abstract pathname into a URL by first converting it into a URI, via the
     681      * {@link #toURI() toURI} method, and then converting the URI into a URL
     682      * via the {@link java.net.URI#toURL() URI.toURL} method.
     683      */
     684     @Deprecated
     685     public URL toURL() throws MalformedURLException {
     686         if (isInvalid()) {
     687             throw new MalformedURLException("Invalid file path");
     688         }
     689         return new URL("file", "", slashify(getAbsolutePath(), isDirectory()));
     690     }
     691
     692     /**
     693      * Constructs a {@code file:} URI that represents this abstract pathname.
     694      *
     695      * <p> The exact form of the URI is system-dependent.  If it can be
     696      * determined that the file denoted by this abstract pathname is a
     697      * directory, then the resulting URI will end with a slash.
     698      *
     699      * <p> For a given abstract pathname <i>f</i>, it is guaranteed that
     700      *
     701      * <blockquote><code>
     702      * new {@link #File(java.net.URI) File}(</code><i>&nbsp;f</i><code>.toURI()).equals(
     703      * </code><i>&nbsp;f</i><code>.{@link #getAbsoluteFile() getAbsoluteFile}())
     704      * </code></blockquote>
     705      *
     706      * so long as the original abstract pathname, the URI, and the new abstract
     707      * pathname are all created in (possibly different invocations of) the same
     708      * Java virtual machine.  Due to the system-dependent nature of abstract
     709      * pathnames, however, this relationship typically does not hold when a
     710      * {@code file:} URI that is created in a virtual machine on one operating
     711      * system is converted into an abstract pathname in a virtual machine on a
     712      * different operating system.
     713      *
     714      * <p> Note that when this abstract pathname represents a UNC pathname then
     715      * all components of the UNC (including the server name component) are encoded
     716      * in the {@code URI} path. The authority component is undefined, meaning
     717      * that it is represented as {@code null}. The {@link Path} class defines the
     718      * {@link Path#toUri toUri} method to encode the server name in the authority
     719      * component of the resulting {@code URI}. The {@link #toPath toPath} method
     720      * may be used to obtain a {@code Path} representing this abstract pathname.
     721      *
     722      * @return  An absolute, hierarchical URI with a scheme equal to
     723      *          {@code "file"}, a path representing this abstract pathname,
     724      *          and undefined authority, query, and fragment components
     725      * @throws SecurityException If a required system property value cannot
     726      * be accessed.
     727      *
     728      * @see #File(java.net.URI)
     729      * @see java.net.URI
     730      * @see java.net.URI#toURL()
     731      * @since 1.4
     732      */
     733     public URI toURI() {
     734         try {
     735             File f = getAbsoluteFile();
     736             String sp = slashify(f.getPath(), f.isDirectory());
     737             if (sp.startsWith("//"))
     738                 sp = "//" + sp;
     739             return new URI("file", null, sp, null);
     740         } catch (URISyntaxException x) {
     741             throw new Error(x);         // Can't happen
     742         }
     743     }
     744
     745
     746     /* -- Attribute accessors -- */
     747
     748     /**
     749      * Tests whether the application can read the file denoted by this
     750      * abstract pathname. On some platforms it may be possible to start the
     751      * Java virtual machine with special privileges that allow it to read
     752      * files that are marked as unreadable. Consequently this method may return
     753      * {@code true} even though the file does not have read permissions.
     754      *
     755      * @return  {@code true} if and only if the file specified by this
     756      *          abstract pathname exists <em>and</em> can be read by the
     757      *          application; {@code false} otherwise
     758      *
     759      * @throws  SecurityException
     760      *          If a security manager exists and its {@link
     761      *          java.lang.SecurityManager#checkRead(java.lang.String)}
     762      *          method denies read access to the file
     763      */
     764     public boolean canRead() {
     765         SecurityManager security = System.getSecurityManager();
     766         if (security != null) {
     767             security.checkRead(path);
     768         }
     769         if (isInvalid()) {
     770             return false;
     771         }
     772         return fs.checkAccess(this, FileSystem.ACCESS_READ);
     773     }
     774
     775     /**
     776      * Tests whether the application can modify the file denoted by this
     777      * abstract pathname. On some platforms it may be possible to start the
     778      * Java virtual machine with special privileges that allow it to modify
     779      * files that are marked read-only. Consequently this method may return
     780      * {@code true} even though the file is marked read-only.
     781      *
     782      * @return  {@code true} if and only if the file system actually
     783      *          contains a file denoted by this abstract pathname <em>and</em>
     784      *          the application is allowed to write to the file;
     785      *          {@code false} otherwise.
     786      *
     787      * @throws  SecurityException
     788      *          If a security manager exists and its {@link
     789      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
     790      *          method denies write access to the file
     791      */
     792     public boolean canWrite() {
     793         SecurityManager security = System.getSecurityManager();
     794         if (security != null) {
     795             security.checkWrite(path);
     796         }
     797         if (isInvalid()) {
     798             return false;
     799         }
     800         return fs.checkAccess(this, FileSystem.ACCESS_WRITE);
     801     }
     802
     803     /**
     804      * Tests whether the file or directory denoted by this abstract pathname
     805      * exists.
     806      *
     807      * @return  {@code true} if and only if the file or directory denoted
     808      *          by this abstract pathname exists; {@code false} otherwise
     809      *
     810      * @throws  SecurityException
     811      *          If a security manager exists and its {@link
     812      *          java.lang.SecurityManager#checkRead(java.lang.String)}
     813      *          method denies read access to the file or directory
     814      */
     815     public boolean exists() {
     816         SecurityManager security = System.getSecurityManager();
     817         if (security != null) {
     818             security.checkRead(path);
     819         }
     820         if (isInvalid()) {
     821             return false;
     822         }
     823         return fs.hasBooleanAttributes(this, FileSystem.BA_EXISTS);
     824     }
     825
     826     /**
     827      * Tests whether the file denoted by this abstract pathname is a
     828      * directory.
     829      *
     830      * <p> Where it is required to distinguish an I/O exception from the case
     831      * that the file is not a directory, or where several attributes of the
     832      * same file are required at the same time, then the {@link
     833      * java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
     834      * Files.readAttributes} method may be used.
     835      *
     836      * @return {@code true} if and only if the file denoted by this
     837      *          abstract pathname exists <em>and</em> is a directory;
     838      *          {@code false} otherwise
     839      *
     840      * @throws  SecurityException
     841      *          If a security manager exists and its {@link
     842      *          java.lang.SecurityManager#checkRead(java.lang.String)}
     843      *          method denies read access to the file
     844      */
     845     public boolean isDirectory() {
     846         SecurityManager security = System.getSecurityManager();
     847         if (security != null) {
     848             security.checkRead(path);
     849         }
     850         if (isInvalid()) {
     851             return false;
     852         }
     853         return fs.hasBooleanAttributes(this, FileSystem.BA_DIRECTORY);
     854     }
     855
     856     /**
     857      * Tests whether the file denoted by this abstract pathname is a normal
     858      * file.  A file is <em>normal</em> if it is not a directory and, in
     859      * addition, satisfies other system-dependent criteria.  Any non-directory
     860      * file created by a Java application is guaranteed to be a normal file.
     861      *
     862      * <p> Where it is required to distinguish an I/O exception from the case
     863      * that the file is not a normal file, or where several attributes of the
     864      * same file are required at the same time, then the {@link
     865      * java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
     866      * Files.readAttributes} method may be used.
     867      *
     868      * @return  {@code true} if and only if the file denoted by this
     869      *          abstract pathname exists <em>and</em> is a normal file;
     870      *          {@code false} otherwise
     871      *
     872      * @throws  SecurityException
     873      *          If a security manager exists and its {@link
     874      *          java.lang.SecurityManager#checkRead(java.lang.String)}
     875      *          method denies read access to the file
     876      */
     877     public boolean isFile() {
     878         SecurityManager security = System.getSecurityManager();
     879         if (security != null) {
     880             security.checkRead(path);
     881         }
     882         if (isInvalid()) {
     883             return false;
     884         }
     885         return fs.hasBooleanAttributes(this, FileSystem.BA_REGULAR);
     886     }
     887
     888     /**
     889      * Tests whether the file named by this abstract pathname is a hidden
     890      * file.  The exact definition of <em>hidden</em> is system-dependent.  On
     891      * UNIX systems, a file is considered to be hidden if its name begins with
     892      * a period character ({@code '.'}).  On Microsoft Windows systems, a file is
     893      * considered to be hidden if it has been marked as such in the filesystem.
     894      *
     895      * @return  {@code true} if and only if the file denoted by this
     896      *          abstract pathname is hidden according to the conventions of the
     897      *          underlying platform
     898      *
     899      * @throws  SecurityException
     900      *          If a security manager exists and its {@link
     901      *          java.lang.SecurityManager#checkRead(java.lang.String)}
     902      *          method denies read access to the file
     903      *
     904      * @since 1.2
     905      */
     906     public boolean isHidden() {
     907         SecurityManager security = System.getSecurityManager();
     908         if (security != null) {
     909             security.checkRead(path);
     910         }
     911         if (isInvalid()) {
     912             return false;
     913         }
     914         return fs.hasBooleanAttributes(this, FileSystem.BA_HIDDEN);
     915     }
     916
     917     /**
     918      * Returns the time that the file denoted by this abstract pathname was
     919      * last modified.
     920      *
     921      * @apiNote
     922      * While the unit of time of the return value is milliseconds, the
     923      * granularity of the value depends on the underlying file system and may
     924      * be larger.  For example, some file systems use time stamps in units of
     925      * seconds.
     926      *
     927      * <p> Where it is required to distinguish an I/O exception from the case
     928      * where {@code 0L} is returned, or where several attributes of the
     929      * same file are required at the same time, or where the time of last
     930      * access or the creation time are required, then the {@link
     931      * java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
     932      * Files.readAttributes} method may be used.  If however only the
     933      * time of last modification is required, then the
     934      * {@link java.nio.file.Files#getLastModifiedTime(Path,LinkOption[])
     935      * Files.getLastModifiedTime} method may be used instead.
     936      *
     937      * @return  A {@code long} value representing the time the file was
     938      *          last modified, measured in milliseconds since the epoch
     939      *          (00:00:00 GMT, January 1, 1970), or {@code 0L} if the
     940      *          file does not exist or if an I/O error occurs.  The value may
     941      *          be negative indicating the number of milliseconds before the
     942      *          epoch
     943      *
     944      * @throws  SecurityException
     945      *          If a security manager exists and its {@link
     946      *          java.lang.SecurityManager#checkRead(java.lang.String)}
     947      *          method denies read access to the file
     948      */
     949     public long lastModified() {
     950         SecurityManager security = System.getSecurityManager();
     951         if (security != null) {
     952             security.checkRead(path);
     953         }
     954         if (isInvalid()) {
     955             return 0L;
     956         }
     957         return fs.getLastModifiedTime(this);
     958     }
     959
     960     /**
     961      * Returns the length of the file denoted by this abstract pathname.
     962      * The return value is unspecified if this pathname denotes a directory.
     963      *
     964      * <p> Where it is required to distinguish an I/O exception from the case
     965      * that {@code 0L} is returned, or where several attributes of the same file
     966      * are required at the same time, then the {@link
     967      * java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
     968      * Files.readAttributes} method may be used.
     969      *
     970      * @return  The length, in bytes, of the file denoted by this abstract
     971      *          pathname, or {@code 0L} if the file does not exist.  Some
     972      *          operating systems may return {@code 0L} for pathnames
     973      *          denoting system-dependent entities such as devices or pipes.
     974      *
     975      * @throws  SecurityException
     976      *          If a security manager exists and its {@link
     977      *          java.lang.SecurityManager#checkRead(java.lang.String)}
     978      *          method denies read access to the file
     979      */
     980     public long length() {
     981         SecurityManager security = System.getSecurityManager();
     982         if (security != null) {
     983             security.checkRead(path);
     984         }
     985         if (isInvalid()) {
     986             return 0L;
     987         }
     988         return fs.getLength(this);
     989     }
     990
     991
     992     /* -- File operations -- */
     993
     994     /**
     995      * Atomically creates a new, empty file named by this abstract pathname if
     996      * and only if a file with this name does not yet exist.  The check for the
     997      * existence of the file and the creation of the file if it does not exist
     998      * are a single operation that is atomic with respect to all other
     999      * filesystem activities that might affect the file.
    1000      * <P>
    1001      * Note: this method should <i>not</i> be used for file-locking, as
    1002      * the resulting protocol cannot be made to work reliably. The
    1003      * {@link java.nio.channels.FileLock FileLock}
    1004      * facility should be used instead.
    1005      *
    1006      * @return  {@code true} if the named file does not exist and was
    1007      *          successfully created; {@code false} if the named file
    1008      *          already exists
    1009      *
    1010      * @throws  IOException
    1011      *          If an I/O error occurred
    1012      *
    1013      * @throws  SecurityException
    1014      *          If a security manager exists and its {@link
    1015      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1016      *          method denies write access to the file
    1017      *
    1018      * @since 1.2
    1019      */
    1020     public boolean createNewFile() throws IOException {
    1021         SecurityManager security = System.getSecurityManager();
    1022         if (security != null) security.checkWrite(path);
    1023         if (isInvalid()) {
    1024             throw new IOException("Invalid file path");
    1025         }
    1026         return fs.createFileExclusively(path);
    1027     }
    1028
    1029     /**
    1030      * Deletes the file or directory denoted by this abstract pathname.  If
    1031      * this pathname denotes a directory, then the directory must be empty in
    1032      * order to be deleted.
    1033      *
    1034      * <p> Note that the {@link java.nio.file.Files} class defines the {@link
    1035      * java.nio.file.Files#delete(Path) delete} method to throw an {@link IOException}
    1036      * when a file cannot be deleted. This is useful for error reporting and to
    1037      * diagnose why a file cannot be deleted.
    1038      *
    1039      * @return  {@code true} if and only if the file or directory is
    1040      *          successfully deleted; {@code false} otherwise
    1041      *
    1042      * @throws  SecurityException
    1043      *          If a security manager exists and its {@link
    1044      *          java.lang.SecurityManager#checkDelete} method denies
    1045      *          delete access to the file
    1046      */
    1047     public boolean delete() {
    1048         SecurityManager security = System.getSecurityManager();
    1049         if (security != null) {
    1050             security.checkDelete(path);
    1051         }
    1052         if (isInvalid()) {
    1053             return false;
    1054         }
    1055         return fs.delete(this);
    1056     }
    1057
    1058     /**
    1059      * Requests that the file or directory denoted by this abstract
    1060      * pathname be deleted when the virtual machine terminates.
    1061      * Files (or directories) are deleted in the reverse order that
    1062      * they are registered. Invoking this method to delete a file or
    1063      * directory that is already registered for deletion has no effect.
    1064      * Deletion will be attempted only for normal termination of the
    1065      * virtual machine, as defined by the Java Language Specification.
    1066      *
    1067      * <p> Once deletion has been requested, it is not possible to cancel the
    1068      * request.  This method should therefore be used with care.
    1069      *
    1070      * <P>
    1071      * Note: this method should <i>not</i> be used for file-locking, as
    1072      * the resulting protocol cannot be made to work reliably. The
    1073      * {@link java.nio.channels.FileLock FileLock}
    1074      * facility should be used instead.
    1075      *
    1076      * @throws  SecurityException
    1077      *          If a security manager exists and its {@link
    1078      *          java.lang.SecurityManager#checkDelete} method denies
    1079      *          delete access to the file
    1080      *
    1081      * @see #delete
    1082      *
    1083      * @since 1.2
    1084      */
    1085     public void deleteOnExit() {
    1086         SecurityManager security = System.getSecurityManager();
    1087         if (security != null) {
    1088             security.checkDelete(path);
    1089         }
    1090         if (isInvalid()) {
    1091             return;
    1092         }
    1093         DeleteOnExitHook.add(path);
    1094     }
    1095
    1096     /**
    1097      * Returns an array of strings naming the files and directories in the
    1098      * directory denoted by this abstract pathname.
    1099      *
    1100      * <p> If this abstract pathname does not denote a directory, then this
    1101      * method returns {@code null}.  Otherwise an array of strings is
    1102      * returned, one for each file or directory in the directory.  Names
    1103      * denoting the directory itself and the directory's parent directory are
    1104      * not included in the result.  Each string is a file name rather than a
    1105      * complete path.
    1106      *
    1107      * <p> There is no guarantee that the name strings in the resulting array
    1108      * will appear in any specific order; they are not, in particular,
    1109      * guaranteed to appear in alphabetical order.
    1110      *
    1111      * <p> Note that the {@link java.nio.file.Files} class defines the {@link
    1112      * java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method to
    1113      * open a directory and iterate over the names of the files in the directory.
    1114      * This may use less resources when working with very large directories, and
    1115      * may be more responsive when working with remote directories.
    1116      *
    1117      * @return  An array of strings naming the files and directories in the
    1118      *          directory denoted by this abstract pathname.  The array will be
    1119      *          empty if the directory is empty.  Returns {@code null} if
    1120      *          this abstract pathname does not denote a directory, or if an
    1121      *          I/O error occurs.
    1122      *
    1123      * @throws  SecurityException
    1124      *          If a security manager exists and its {@link
    1125      *          SecurityManager#checkRead(String)} method denies read access to
    1126      *          the directory
    1127      */
    1128     public String[] list() {
    1129         SecurityManager security = System.getSecurityManager();
    1130         if (security != null) {
    1131             security.checkRead(path);
    1132         }
    1133         if (isInvalid()) {
    1134             return null;
    1135         }
    1136         return fs.list(this);
    1137     }
    1138
    1139     /**
    1140      * Returns an array of strings naming the files and directories in the
    1141      * directory denoted by this abstract pathname that satisfy the specified
    1142      * filter.  The behavior of this method is the same as that of the
    1143      * {@link #list()} method, except that the strings in the returned array
    1144      * must satisfy the filter.  If the given {@code filter} is {@code null}
    1145      * then all names are accepted.  Otherwise, a name satisfies the filter if
    1146      * and only if the value {@code true} results when the {@link
    1147      * FilenameFilter#accept FilenameFilter.accept(File,&nbsp;String)} method
    1148      * of the filter is invoked on this abstract pathname and the name of a
    1149      * file or directory in the directory that it denotes.
    1150      *
    1151      * @param  filter
    1152      *         A filename filter
    1153      *
    1154      * @return  An array of strings naming the files and directories in the
    1155      *          directory denoted by this abstract pathname that were accepted
    1156      *          by the given {@code filter}.  The array will be empty if the
    1157      *          directory is empty or if no names were accepted by the filter.
    1158      *          Returns {@code null} if this abstract pathname does not denote
    1159      *          a directory, or if an I/O error occurs.
    1160      *
    1161      * @throws  SecurityException
    1162      *          If a security manager exists and its {@link
    1163      *          SecurityManager#checkRead(String)} method denies read access to
    1164      *          the directory
    1165      *
    1166      * @see java.nio.file.Files#newDirectoryStream(Path,String)
    1167      */
    1168     public String[] list(FilenameFilter filter) {
    1169         String names[] = list();
    1170         if ((names == null) || (filter == null)) {
    1171             return names;
    1172         }
    1173         List<String> v = new ArrayList<>();
    1174         for (int i = 0 ; i < names.length ; i++) {
    1175             if (filter.accept(this, names[i])) {
    1176                 v.add(names[i]);
    1177             }
    1178         }
    1179         return v.toArray(new String[v.size()]);
    1180     }
    1181
    1182     /**
    1183      * Returns an array of abstract pathnames denoting the files in the
    1184      * directory denoted by this abstract pathname.
    1185      *
    1186      * <p> If this abstract pathname does not denote a directory, then this
    1187      * method returns {@code null}.  Otherwise an array of {@code File} objects
    1188      * is returned, one for each file or directory in the directory.  Pathnames
    1189      * denoting the directory itself and the directory's parent directory are
    1190      * not included in the result.  Each resulting abstract pathname is
    1191      * constructed from this abstract pathname using the {@link #File(File,
    1192      * String) File(File,&nbsp;String)} constructor.  Therefore if this
    1193      * pathname is absolute then each resulting pathname is absolute; if this
    1194      * pathname is relative then each resulting pathname will be relative to
    1195      * the same directory.
    1196      *
    1197      * <p> There is no guarantee that the name strings in the resulting array
    1198      * will appear in any specific order; they are not, in particular,
    1199      * guaranteed to appear in alphabetical order.
    1200      *
    1201      * <p> Note that the {@link java.nio.file.Files} class defines the {@link
    1202      * java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method
    1203      * to open a directory and iterate over the names of the files in the
    1204      * directory. This may use less resources when working with very large
    1205      * directories.
    1206      *
    1207      * @return  An array of abstract pathnames denoting the files and
    1208      *          directories in the directory denoted by this abstract pathname.
    1209      *          The array will be empty if the directory is empty.  Returns
    1210      *          {@code null} if this abstract pathname does not denote a
    1211      *          directory, or if an I/O error occurs.
    1212      *
    1213      * @throws  SecurityException
    1214      *          If a security manager exists and its {@link
    1215      *          SecurityManager#checkRead(String)} method denies read access to
    1216      *          the directory
    1217      *
    1218      * @since  1.2
    1219      */
    1220     public File[] listFiles() {
    1221         String[] ss = list();
    1222         if (ss == null) return null;
    1223         int n = ss.length;
    1224         File[] fs = new File[n];
    1225         for (int i = 0; i < n; i++) {
    1226             fs[i] = new File(ss[i], this);
    1227         }
    1228         return fs;
    1229     }
    1230
    1231     /**
    1232      * Returns an array of abstract pathnames denoting the files and
    1233      * directories in the directory denoted by this abstract pathname that
    1234      * satisfy the specified filter.  The behavior of this method is the same
    1235      * as that of the {@link #listFiles()} method, except that the pathnames in
    1236      * the returned array must satisfy the filter.  If the given {@code filter}
    1237      * is {@code null} then all pathnames are accepted.  Otherwise, a pathname
    1238      * satisfies the filter if and only if the value {@code true} results when
    1239      * the {@link FilenameFilter#accept
    1240      * FilenameFilter.accept(File,&nbsp;String)} method of the filter is
    1241      * invoked on this abstract pathname and the name of a file or directory in
    1242      * the directory that it denotes.
    1243      *
    1244      * @param  filter
    1245      *         A filename filter
    1246      *
    1247      * @return  An array of abstract pathnames denoting the files and
    1248      *          directories in the directory denoted by this abstract pathname.
    1249      *          The array will be empty if the directory is empty.  Returns
    1250      *          {@code null} if this abstract pathname does not denote a
    1251      *          directory, or if an I/O error occurs.
    1252      *
    1253      * @throws  SecurityException
    1254      *          If a security manager exists and its {@link
    1255      *          SecurityManager#checkRead(String)} method denies read access to
    1256      *          the directory
    1257      *
    1258      * @since  1.2
    1259      * @see java.nio.file.Files#newDirectoryStream(Path,String)
    1260      */
    1261     public File[] listFiles(FilenameFilter filter) {
    1262         String ss[] = list();
    1263         if (ss == null) return null;
    1264         ArrayList<File> files = new ArrayList<>();
    1265         for (String s : ss)
    1266             if ((filter == null) || filter.accept(this, s))
    1267                 files.add(new File(s, this));
    1268         return files.toArray(new File[files.size()]);
    1269     }
    1270
    1271     /**
    1272      * Returns an array of abstract pathnames denoting the files and
    1273      * directories in the directory denoted by this abstract pathname that
    1274      * satisfy the specified filter.  The behavior of this method is the same
    1275      * as that of the {@link #listFiles()} method, except that the pathnames in
    1276      * the returned array must satisfy the filter.  If the given {@code filter}
    1277      * is {@code null} then all pathnames are accepted.  Otherwise, a pathname
    1278      * satisfies the filter if and only if the value {@code true} results when
    1279      * the {@link FileFilter#accept FileFilter.accept(File)} method of the
    1280      * filter is invoked on the pathname.
    1281      *
    1282      * @param  filter
    1283      *         A file filter
    1284      *
    1285      * @return  An array of abstract pathnames denoting the files and
    1286      *          directories in the directory denoted by this abstract pathname.
    1287      *          The array will be empty if the directory is empty.  Returns
    1288      *          {@code null} if this abstract pathname does not denote a
    1289      *          directory, or if an I/O error occurs.
    1290      *
    1291      * @throws  SecurityException
    1292      *          If a security manager exists and its {@link
    1293      *          SecurityManager#checkRead(String)} method denies read access to
    1294      *          the directory
    1295      *
    1296      * @since  1.2
    1297      * @see java.nio.file.Files#newDirectoryStream(Path,java.nio.file.DirectoryStream.Filter)
    1298      */
    1299     public File[] listFiles(FileFilter filter) {
    1300         String ss[] = list();
    1301         if (ss == null) return null;
    1302         ArrayList<File> files = new ArrayList<>();
    1303         for (String s : ss) {
    1304             File f = new File(s, this);
    1305             if ((filter == null) || filter.accept(f))
    1306                 files.add(f);
    1307         }
    1308         return files.toArray(new File[files.size()]);
    1309     }
    1310
    1311     /**
    1312      * Creates the directory named by this abstract pathname.
    1313      *
    1314      * @return  {@code true} if and only if the directory was
    1315      *          created; {@code false} otherwise
    1316      *
    1317      * @throws  SecurityException
    1318      *          If a security manager exists and its {@link
    1319      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1320      *          method does not permit the named directory to be created
    1321      */
    1322     public boolean mkdir() {
    1323         SecurityManager security = System.getSecurityManager();
    1324         if (security != null) {
    1325             security.checkWrite(path);
    1326         }
    1327         if (isInvalid()) {
    1328             return false;
    1329         }
    1330         return fs.createDirectory(this);
    1331     }
    1332
    1333     /**
    1334      * Creates the directory named by this abstract pathname, including any
    1335      * necessary but nonexistent parent directories.  Note that if this
    1336      * operation fails it may have succeeded in creating some of the necessary
    1337      * parent directories.
    1338      *
    1339      * @return  {@code true} if and only if the directory was created,
    1340      *          along with all necessary parent directories; {@code false}
    1341      *          otherwise
    1342      *
    1343      * @throws  SecurityException
    1344      *          If a security manager exists and its {@link
    1345      *          java.lang.SecurityManager#checkRead(java.lang.String)}
    1346      *          method does not permit verification of the existence of the
    1347      *          named directory and all necessary parent directories; or if
    1348      *          the {@link
    1349      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1350      *          method does not permit the named directory and all necessary
    1351      *          parent directories to be created
    1352      */
    1353     public boolean mkdirs() {
    1354         if (exists()) {
    1355             return false;
    1356         }
    1357         if (mkdir()) {
    1358             return true;
    1359         }
    1360         File canonFile = null;
    1361         try {
    1362             canonFile = getCanonicalFile();
    1363         } catch (IOException e) {
    1364             return false;
    1365         }
    1366
    1367         File parent = canonFile.getParentFile();
    1368         return (parent != null && (parent.mkdirs() || parent.exists()) &&
    1369                 canonFile.mkdir());
    1370     }
    1371
    1372     /**
    1373      * Renames the file denoted by this abstract pathname.
    1374      *
    1375      * <p> Many aspects of the behavior of this method are inherently
    1376      * platform-dependent: The rename operation might not be able to move a
    1377      * file from one filesystem to another, it might not be atomic, and it
    1378      * might not succeed if a file with the destination abstract pathname
    1379      * already exists.  The return value should always be checked to make sure
    1380      * that the rename operation was successful.
    1381      *
    1382      * <p> Note that the {@link java.nio.file.Files} class defines the {@link
    1383      * java.nio.file.Files#move move} method to move or rename a file in a
    1384      * platform independent manner.
    1385      *
    1386      * @param  dest  The new abstract pathname for the named file
    1387      *
    1388      * @return  {@code true} if and only if the renaming succeeded;
    1389      *          {@code false} otherwise
    1390      *
    1391      * @throws  SecurityException
    1392      *          If a security manager exists and its {@link
    1393      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1394      *          method denies write access to either the old or new pathnames
    1395      *
    1396      * @throws  NullPointerException
    1397      *          If parameter {@code dest} is {@code null}
    1398      */
    1399     public boolean renameTo(File dest) {
    1400         if (dest == null) {
    1401             throw new NullPointerException();
    1402         }
    1403         SecurityManager security = System.getSecurityManager();
    1404         if (security != null) {
    1405             security.checkWrite(path);
    1406             security.checkWrite(dest.path);
    1407         }
    1408         if (this.isInvalid() || dest.isInvalid()) {
    1409             return false;
    1410         }
    1411         return fs.rename(this, dest);
    1412     }
    1413
    1414     /**
    1415      * Sets the last-modified time of the file or directory named by this
    1416      * abstract pathname.
    1417      *
    1418      * <p> All platforms support file-modification times to the nearest second,
    1419      * but some provide more precision.  The argument will be truncated to fit
    1420      * the supported precision.  If the operation succeeds and no intervening
    1421      * operations on the file take place, then the next invocation of the
    1422      * {@link #lastModified} method will return the (possibly
    1423      * truncated) {@code time} argument that was passed to this method.
    1424      *
    1425      * @param  time  The new last-modified time, measured in milliseconds since
    1426      *               the epoch (00:00:00 GMT, January 1, 1970)
    1427      *
    1428      * @return {@code true} if and only if the operation succeeded;
    1429      *          {@code false} otherwise
    1430      *
    1431      * @throws  IllegalArgumentException  If the argument is negative
    1432      *
    1433      * @throws  SecurityException
    1434      *          If a security manager exists and its {@link
    1435      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1436      *          method denies write access to the named file
    1437      *
    1438      * @since 1.2
    1439      */
    1440     public boolean setLastModified(long time) {
    1441         if (time < 0) throw new IllegalArgumentException("Negative time");
    1442         SecurityManager security = System.getSecurityManager();
    1443         if (security != null) {
    1444             security.checkWrite(path);
    1445         }
    1446         if (isInvalid()) {
    1447             return false;
    1448         }
    1449         return fs.setLastModifiedTime(this, time);
    1450     }
    1451
    1452     /**
    1453      * Marks the file or directory named by this abstract pathname so that
    1454      * only read operations are allowed. After invoking this method the file
    1455      * or directory will not change until it is either deleted or marked
    1456      * to allow write access. On some platforms it may be possible to start the
    1457      * Java virtual machine with special privileges that allow it to modify
    1458      * files that are marked read-only. Whether or not a read-only file or
    1459      * directory may be deleted depends upon the underlying system.
    1460      *
    1461      * @return {@code true} if and only if the operation succeeded;
    1462      *          {@code false} otherwise
    1463      *
    1464      * @throws  SecurityException
    1465      *          If a security manager exists and its {@link
    1466      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1467      *          method denies write access to the named file
    1468      *
    1469      * @since 1.2
    1470      */
    1471     public boolean setReadOnly() {
    1472         SecurityManager security = System.getSecurityManager();
    1473         if (security != null) {
    1474             security.checkWrite(path);
    1475         }
    1476         if (isInvalid()) {
    1477             return false;
    1478         }
    1479         return fs.setReadOnly(this);
    1480     }
    1481
    1482     /**
    1483      * Sets the owner's or everybody's write permission for this abstract
    1484      * pathname. On some platforms it may be possible to start the Java virtual
    1485      * machine with special privileges that allow it to modify files that
    1486      * disallow write operations.
    1487      *
    1488      * <p> The {@link java.nio.file.Files} class defines methods that operate on
    1489      * file attributes including file permissions. This may be used when finer
    1490      * manipulation of file permissions is required.
    1491      *
    1492      * @param   writable
    1493      *          If {@code true}, sets the access permission to allow write
    1494      *          operations; if {@code false} to disallow write operations
    1495      *
    1496      * @param   ownerOnly
    1497      *          If {@code true}, the write permission applies only to the
    1498      *          owner's write permission; otherwise, it applies to everybody.  If
    1499      *          the underlying file system can not distinguish the owner's write
    1500      *          permission from that of others, then the permission will apply to
    1501      *          everybody, regardless of this value.
    1502      *
    1503      * @return  {@code true} if and only if the operation succeeded. The
    1504      *          operation will fail if the user does not have permission to change
    1505      *          the access permissions of this abstract pathname.
    1506      *
    1507      * @throws  SecurityException
    1508      *          If a security manager exists and its {@link
    1509      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1510      *          method denies write access to the named file
    1511      *
    1512      * @since 1.6
    1513      */
    1514     public boolean setWritable(boolean writable, boolean ownerOnly) {
    1515         SecurityManager security = System.getSecurityManager();
    1516         if (security != null) {
    1517             security.checkWrite(path);
    1518         }
    1519         if (isInvalid()) {
    1520             return false;
    1521         }
    1522         return fs.setPermission(this, FileSystem.ACCESS_WRITE, writable, ownerOnly);
    1523     }
    1524
    1525     /**
    1526      * A convenience method to set the owner's write permission for this abstract
    1527      * pathname. On some platforms it may be possible to start the Java virtual
    1528      * machine with special privileges that allow it to modify files that
    1529      * disallow write operations.
    1530      *
    1531      * <p> An invocation of this method of the form {@code file.setWritable(arg)}
    1532      * behaves in exactly the same way as the invocation
    1533      *
    1534      * <pre>{@code
    1535      *     file.setWritable(arg, true)
    1536      * }</pre>
    1537      *
    1538      * @param   writable
    1539      *          If {@code true}, sets the access permission to allow write
    1540      *          operations; if {@code false} to disallow write operations
    1541      *
    1542      * @return  {@code true} if and only if the operation succeeded.  The
    1543      *          operation will fail if the user does not have permission to
    1544      *          change the access permissions of this abstract pathname.
    1545      *
    1546      * @throws  SecurityException
    1547      *          If a security manager exists and its {@link
    1548      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1549      *          method denies write access to the file
    1550      *
    1551      * @since 1.6
    1552      */
    1553     public boolean setWritable(boolean writable) {
    1554         return setWritable(writable, true);
    1555     }
    1556
    1557     /**
    1558      * Sets the owner's or everybody's read permission for this abstract
    1559      * pathname. On some platforms it may be possible to start the Java virtual
    1560      * machine with special privileges that allow it to read files that are
    1561      * marked as unreadable.
    1562      *
    1563      * <p> The {@link java.nio.file.Files} class defines methods that operate on
    1564      * file attributes including file permissions. This may be used when finer
    1565      * manipulation of file permissions is required.
    1566      *
    1567      * @param   readable
    1568      *          If {@code true}, sets the access permission to allow read
    1569      *          operations; if {@code false} to disallow read operations
    1570      *
    1571      * @param   ownerOnly
    1572      *          If {@code true}, the read permission applies only to the
    1573      *          owner's read permission; otherwise, it applies to everybody.  If
    1574      *          the underlying file system can not distinguish the owner's read
    1575      *          permission from that of others, then the permission will apply to
    1576      *          everybody, regardless of this value.
    1577      *
    1578      * @return  {@code true} if and only if the operation succeeded.  The
    1579      *          operation will fail if the user does not have permission to
    1580      *          change the access permissions of this abstract pathname.  If
    1581      *          {@code readable} is {@code false} and the underlying
    1582      *          file system does not implement a read permission, then the
    1583      *          operation will fail.
    1584      *
    1585      * @throws  SecurityException
    1586      *          If a security manager exists and its {@link
    1587      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1588      *          method denies write access to the file
    1589      *
    1590      * @since 1.6
    1591      */
    1592     public boolean setReadable(boolean readable, boolean ownerOnly) {
    1593         SecurityManager security = System.getSecurityManager();
    1594         if (security != null) {
    1595             security.checkWrite(path);
    1596         }
    1597         if (isInvalid()) {
    1598             return false;
    1599         }
    1600         return fs.setPermission(this, FileSystem.ACCESS_READ, readable, ownerOnly);
    1601     }
    1602
    1603     /**
    1604      * A convenience method to set the owner's read permission for this abstract
    1605      * pathname. On some platforms it may be possible to start the Java virtual
    1606      * machine with special privileges that allow it to read files that are
    1607      * marked as unreadable.
    1608      *
    1609      * <p>An invocation of this method of the form {@code file.setReadable(arg)}
    1610      * behaves in exactly the same way as the invocation
    1611      *
    1612      * <pre>{@code
    1613      *     file.setReadable(arg, true)
    1614      * }</pre>
    1615      *
    1616      * @param  readable
    1617      *          If {@code true}, sets the access permission to allow read
    1618      *          operations; if {@code false} to disallow read operations
    1619      *
    1620      * @return  {@code true} if and only if the operation succeeded.  The
    1621      *          operation will fail if the user does not have permission to
    1622      *          change the access permissions of this abstract pathname.  If
    1623      *          {@code readable} is {@code false} and the underlying
    1624      *          file system does not implement a read permission, then the
    1625      *          operation will fail.
    1626      *
    1627      * @throws  SecurityException
    1628      *          If a security manager exists and its {@link
    1629      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1630      *          method denies write access to the file
    1631      *
    1632      * @since 1.6
    1633      */
    1634     public boolean setReadable(boolean readable) {
    1635         return setReadable(readable, true);
    1636     }
    1637
    1638     /**
    1639      * Sets the owner's or everybody's execute permission for this abstract
    1640      * pathname. On some platforms it may be possible to start the Java virtual
    1641      * machine with special privileges that allow it to execute files that are
    1642      * not marked executable.
    1643      *
    1644      * <p> The {@link java.nio.file.Files} class defines methods that operate on
    1645      * file attributes including file permissions. This may be used when finer
    1646      * manipulation of file permissions is required.
    1647      *
    1648      * @param   executable
    1649      *          If {@code true}, sets the access permission to allow execute
    1650      *          operations; if {@code false} to disallow execute operations
    1651      *
    1652      * @param   ownerOnly
    1653      *          If {@code true}, the execute permission applies only to the
    1654      *          owner's execute permission; otherwise, it applies to everybody.
    1655      *          If the underlying file system can not distinguish the owner's
    1656      *          execute permission from that of others, then the permission will
    1657      *          apply to everybody, regardless of this value.
    1658      *
    1659      * @return  {@code true} if and only if the operation succeeded.  The
    1660      *          operation will fail if the user does not have permission to
    1661      *          change the access permissions of this abstract pathname.  If
    1662      *          {@code executable} is {@code false} and the underlying
    1663      *          file system does not implement an execute permission, then the
    1664      *          operation will fail.
    1665      *
    1666      * @throws  SecurityException
    1667      *          If a security manager exists and its {@link
    1668      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1669      *          method denies write access to the file
    1670      *
    1671      * @since 1.6
    1672      */
    1673     public boolean setExecutable(boolean executable, boolean ownerOnly) {
    1674         SecurityManager security = System.getSecurityManager();
    1675         if (security != null) {
    1676             security.checkWrite(path);
    1677         }
    1678         if (isInvalid()) {
    1679             return false;
    1680         }
    1681         return fs.setPermission(this, FileSystem.ACCESS_EXECUTE, executable, ownerOnly);
    1682     }
    1683
    1684     /**
    1685      * A convenience method to set the owner's execute permission for this
    1686      * abstract pathname. On some platforms it may be possible to start the Java
    1687      * virtual machine with special privileges that allow it to execute files
    1688      * that are not marked executable.
    1689      *
    1690      * <p>An invocation of this method of the form {@code file.setExcutable(arg)}
    1691      * behaves in exactly the same way as the invocation
    1692      *
    1693      * <pre>{@code
    1694      *     file.setExecutable(arg, true)
    1695      * }</pre>
    1696      *
    1697      * @param   executable
    1698      *          If {@code true}, sets the access permission to allow execute
    1699      *          operations; if {@code false} to disallow execute operations
    1700      *
    1701      * @return   {@code true} if and only if the operation succeeded.  The
    1702      *           operation will fail if the user does not have permission to
    1703      *           change the access permissions of this abstract pathname.  If
    1704      *           {@code executable} is {@code false} and the underlying
    1705      *           file system does not implement an execute permission, then the
    1706      *           operation will fail.
    1707      *
    1708      * @throws  SecurityException
    1709      *          If a security manager exists and its {@link
    1710      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    1711      *          method denies write access to the file
    1712      *
    1713      * @since 1.6
    1714      */
    1715     public boolean setExecutable(boolean executable) {
    1716         return setExecutable(executable, true);
    1717     }
    1718
    1719     /**
    1720      * Tests whether the application can execute the file denoted by this
    1721      * abstract pathname. On some platforms it may be possible to start the
    1722      * Java virtual machine with special privileges that allow it to execute
    1723      * files that are not marked executable. Consequently this method may return
    1724      * {@code true} even though the file does not have execute permissions.
    1725      *
    1726      * @return  {@code true} if and only if the abstract pathname exists
    1727      *          <em>and</em> the application is allowed to execute the file
    1728      *
    1729      * @throws  SecurityException
    1730      *          If a security manager exists and its {@link
    1731      *          java.lang.SecurityManager#checkExec(java.lang.String)}
    1732      *          method denies execute access to the file
    1733      *
    1734      * @since 1.6
    1735      */
    1736     public boolean canExecute() {
    1737         SecurityManager security = System.getSecurityManager();
    1738         if (security != null) {
    1739             security.checkExec(path);
    1740         }
    1741         if (isInvalid()) {
    1742             return false;
    1743         }
    1744         return fs.checkAccess(this, FileSystem.ACCESS_EXECUTE);
    1745     }
    1746
    1747
    1748     /* -- Filesystem interface -- */
    1749
    1750     /**
    1751      * List the available filesystem roots.
    1752      *
    1753      * <p> A particular Java platform may support zero or more
    1754      * hierarchically-organized file systems.  Each file system has a
    1755      * {@code root} directory from which all other files in that file system
    1756      * can be reached.  Windows platforms, for example, have a root directory
    1757      * for each active drive; UNIX platforms have a single root directory,
    1758      * namely {@code "/"}.  The set of available filesystem roots is affected
    1759      * by various system-level operations such as the insertion or ejection of
    1760      * removable media and the disconnecting or unmounting of physical or
    1761      * virtual disk drives.
    1762      *
    1763      * <p> This method returns an array of {@code File} objects that denote the
    1764      * root directories of the available filesystem roots.  It is guaranteed
    1765      * that the canonical pathname of any file physically present on the local
    1766      * machine will begin with one of the roots returned by this method.
    1767      *
    1768      * <p> The canonical pathname of a file that resides on some other machine
    1769      * and is accessed via a remote-filesystem protocol such as SMB or NFS may
    1770      * or may not begin with one of the roots returned by this method.  If the
    1771      * pathname of a remote file is syntactically indistinguishable from the
    1772      * pathname of a local file then it will begin with one of the roots
    1773      * returned by this method.  Thus, for example, {@code File} objects
    1774      * denoting the root directories of the mapped network drives of a Windows
    1775      * platform will be returned by this method, while {@code File} objects
    1776      * containing UNC pathnames will not be returned by this method.
    1777      *
    1778      * <p> Unlike most methods in this class, this method does not throw
    1779      * security exceptions.  If a security manager exists and its {@link
    1780      * SecurityManager#checkRead(String)} method denies read access to a
    1781      * particular root directory, then that directory will not appear in the
    1782      * result.
    1783      *
    1784      * @return  An array of {@code File} objects denoting the available
    1785      *          filesystem roots, or {@code null} if the set of roots could not
    1786      *          be determined.  The array will be empty if there are no
    1787      *          filesystem roots.
    1788      *
    1789      * @since  1.2
    1790      * @see java.nio.file.FileStore
    1791      */
    1792     public static File[] listRoots() {
    1793         return fs.listRoots();
    1794     }
    1795
    1796
    1797     /* -- Disk usage -- */
    1798
    1799     /**
    1800      * Returns the size of the partition <a href="#partName">named</a> by this
    1801      * abstract pathname. If the total number of bytes in the partition is
    1802      * greater than {@link Long#MAX_VALUE}, then {@code Long.MAX_VALUE} will be
    1803      * returned.
    1804      *
    1805      * @return  The size, in bytes, of the partition or {@code 0L} if this
    1806      *          abstract pathname does not name a partition or if the size
    1807      *          cannot be obtained
    1808      *
    1809      * @throws  SecurityException
    1810      *          If a security manager has been installed and it denies
    1811      *          {@link RuntimePermission}{@code ("getFileSystemAttributes")}
    1812      *          or its {@link SecurityManager#checkRead(String)} method denies
    1813      *          read access to the file named by this abstract pathname
    1814      *
    1815      * @since  1.6
    1816      * @see FileStore#getTotalSpace
    1817      */
    1818     public long getTotalSpace() {
    1819         SecurityManager sm = System.getSecurityManager();
    1820         if (sm != null) {
    1821             sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
    1822             sm.checkRead(path);
    1823         }
    1824         if (isInvalid()) {
    1825             return 0L;
    1826         }
    1827         long space = fs.getSpace(this, FileSystem.SPACE_TOTAL);
    1828         return space >= 0L ? space : Long.MAX_VALUE;
    1829     }
    1830
    1831     /**
    1832      * Returns the number of unallocated bytes in the partition <a
    1833      * href="#partName">named</a> by this abstract path name.  If the
    1834      * number of unallocated bytes in the partition is greater than
    1835      * {@link Long#MAX_VALUE}, then {@code Long.MAX_VALUE} will be returned.
    1836      *
    1837      * <p> The returned number of unallocated bytes is a hint, but not
    1838      * a guarantee, that it is possible to use most or any of these
    1839      * bytes.  The number of unallocated bytes is most likely to be
    1840      * accurate immediately after this call.  It is likely to be made
    1841      * inaccurate by any external I/O operations including those made
    1842      * on the system outside of this virtual machine.  This method
    1843      * makes no guarantee that write operations to this file system
    1844      * will succeed.
    1845      *
    1846      * @return  The number of unallocated bytes on the partition or {@code 0L}
    1847      *          if the abstract pathname does not name a partition or if this
    1848      *          number cannot be obtained.  This value will be less than or
    1849      *          equal to the total file system size returned by
    1850      *          {@link #getTotalSpace}.
    1851      *
    1852      * @throws  SecurityException
    1853      *          If a security manager has been installed and it denies
    1854      *          {@link RuntimePermission}{@code ("getFileSystemAttributes")}
    1855      *          or its {@link SecurityManager#checkRead(String)} method denies
    1856      *          read access to the file named by this abstract pathname
    1857      *
    1858      * @since  1.6
    1859      * @see FileStore#getUnallocatedSpace
    1860      */
    1861     public long getFreeSpace() {
    1862         SecurityManager sm = System.getSecurityManager();
    1863         if (sm != null) {
    1864             sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
    1865             sm.checkRead(path);
    1866         }
    1867         if (isInvalid()) {
    1868             return 0L;
    1869         }
    1870         long space = fs.getSpace(this, FileSystem.SPACE_FREE);
    1871         return space >= 0L ? space : Long.MAX_VALUE;
    1872     }
    1873
    1874     /**
    1875      * Returns the number of bytes available to this virtual machine on the
    1876      * partition <a href="#partName">named</a> by this abstract pathname.  If
    1877      * the number of available bytes in the partition is greater than
    1878      * {@link Long#MAX_VALUE}, then {@code Long.MAX_VALUE} will be returned.
    1879      * When possible, this method checks for write permissions and other
    1880      * operating system restrictions and will therefore usually provide a more
    1881      * accurate estimate of how much new data can actually be written than
    1882      * {@link #getFreeSpace}.
    1883      *
    1884      * <p> The returned number of available bytes is a hint, but not a
    1885      * guarantee, that it is possible to use most or any of these bytes.  The
    1886      * number of available bytes is most likely to be accurate immediately
    1887      * after this call.  It is likely to be made inaccurate by any external
    1888      * I/O operations including those made on the system outside of this
    1889      * virtual machine.  This method makes no guarantee that write operations
    1890      * to this file system will succeed.
    1891      *
    1892      * @return  The number of available bytes on the partition or {@code 0L}
    1893      *          if the abstract pathname does not name a partition or if this
    1894      *          number cannot be obtained.  On systems where this information
    1895      *          is not available, this method will be equivalent to a call to
    1896      *          {@link #getFreeSpace}.
    1897      *
    1898      * @throws  SecurityException
    1899      *          If a security manager has been installed and it denies
    1900      *          {@link RuntimePermission}{@code ("getFileSystemAttributes")}
    1901      *          or its {@link SecurityManager#checkRead(String)} method denies
    1902      *          read access to the file named by this abstract pathname
    1903      *
    1904      * @since  1.6
    1905      * @see FileStore#getUsableSpace
    1906      */
    1907     public long getUsableSpace() {
    1908         SecurityManager sm = System.getSecurityManager();
    1909         if (sm != null) {
    1910             sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
    1911             sm.checkRead(path);
    1912         }
    1913         if (isInvalid()) {
    1914             return 0L;
    1915         }
    1916         long space = fs.getSpace(this, FileSystem.SPACE_USABLE);
    1917         return space >= 0L ? space : Long.MAX_VALUE;
    1918     }
    1919
    1920     /* -- Temporary files -- */
    1921
    1922     private static class TempDirectory {
    1923         private TempDirectory() { }
    1924
    1925         // temporary directory location
    1926         private static final File tmpdir = new File(
    1927                 GetPropertyAction.privilegedGetProperty("java.io.tmpdir"));
    1928         static File location() {
    1929             return tmpdir;
    1930         }
    1931
    1932         // file name generation
    1933         private static final SecureRandom random = new SecureRandom();
    1934         private static int shortenSubName(int subNameLength, int excess,
    1935             int nameMin) {
    1936             int newLength = Math.max(nameMin, subNameLength - excess);
    1937             if (newLength < subNameLength) {
    1938                 return newLength;
    1939             }
    1940             return subNameLength;
    1941         }
    1942         static File generateFile(String prefix, String suffix, File dir)
    1943             throws IOException
    1944         {
    1945             long n = random.nextLong();
    1946             String nus = Long.toUnsignedString(n);
    1947
    1948             // Use only the file name from the supplied prefix
    1949             prefix = (new File(prefix)).getName();
    1950
    1951             int prefixLength = prefix.length();
    1952             int nusLength = nus.length();
    1953             int suffixLength = suffix.length();;
    1954
    1955             String name;
    1956             int nameMax = fs.getNameMax(dir.getPath());
    1957             int excess = prefixLength + nusLength + suffixLength - nameMax;
    1958             if (excess <= 0) {
    1959                 name = prefix + nus + suffix;
    1960             } else {
    1961                 // Name exceeds the maximum path component length: shorten it
    1962
    1963                 // Attempt to shorten the prefix length to no less then 3
    1964                 prefixLength = shortenSubName(prefixLength, excess, 3);
    1965                 excess = prefixLength + nusLength + suffixLength - nameMax;
    1966
    1967                 if (excess > 0) {
    1968                     // Attempt to shorten the suffix length to no less than
    1969                     // 0 or 4 depending on whether it begins with a dot ('.')
    1970                     suffixLength = shortenSubName(suffixLength, excess,
    1971                         suffix.indexOf(".") == 0 ? 4 : 0);
    1972                     suffixLength = shortenSubName(suffixLength, excess, 3);
    1973                     excess = prefixLength + nusLength + suffixLength - nameMax;
    1974                 }
    1975
    1976                 if (excess > 0 && excess <= nusLength - 5) {
    1977                     // Attempt to shorten the random character string length
    1978                     // to no less than 5
    1979                     nusLength = shortenSubName(nusLength, excess, 5);
    1980                 }
    1981
    1982                 StringBuilder sb =
    1983                     new StringBuilder(prefixLength + nusLength + suffixLength);
    1984                 sb.append(prefixLength < prefix.length() ?
    1985                     prefix.substring(0, prefixLength) : prefix);
    1986                 sb.append(nusLength < nus.length() ?
    1987                     nus.substring(0, nusLength) : nus);
    1988                 sb.append(suffixLength < suffix.length() ?
    1989                     suffix.substring(0, suffixLength) : suffix);
    1990                 name = sb.toString();
    1991             }
    1992
    1993             // Normalize the path component
    1994             name = fs.normalize(name);
    1995
    1996             File f = new File(dir, name);
    1997             if (!name.equals(f.getName()) || f.isInvalid()) {
    1998                 if (System.getSecurityManager() != null)
    1999                     throw new IOException("Unable to create temporary file");
    2000                 else
    2001                     throw new IOException("Unable to create temporary file, "
    2002                         + name);
    2003             }
    2004             return f;
    2005         }
    2006     }
    2007
    2008     /**
    2009      * <p> Creates a new empty file in the specified directory, using the
    2010      * given prefix and suffix strings to generate its name.  If this method
    2011      * returns successfully then it is guaranteed that:
    2012      *
    2013      * <ol>
    2014      * <li> The file denoted by the returned abstract pathname did not exist
    2015      *      before this method was invoked, and
    2016      * <li> Neither this method nor any of its variants will return the same
    2017      *      abstract pathname again in the current invocation of the virtual
    2018      *      machine.
    2019      * </ol>
    2020      *
    2021      * This method provides only part of a temporary-file facility.  To arrange
    2022      * for a file created by this method to be deleted automatically, use the
    2023      * {@link #deleteOnExit} method.
    2024      *
    2025      * <p> The {@code prefix} argument must be at least three characters
    2026      * long.  It is recommended that the prefix be a short, meaningful string
    2027      * such as {@code "hjb"} or {@code "mail"}.  The
    2028      * {@code suffix} argument may be {@code null}, in which case the
    2029      * suffix {@code ".tmp"} will be used.
    2030      *
    2031      * <p> To create the new file, the prefix and the suffix may first be
    2032      * adjusted to fit the limitations of the underlying platform.  If the
    2033      * prefix is too long then it will be truncated, but its first three
    2034      * characters will always be preserved.  If the suffix is too long then it
    2035      * too will be truncated, but if it begins with a period character
    2036      * ({@code '.'}) then the period and the first three characters
    2037      * following it will always be preserved.  Once these adjustments have been
    2038      * made the name of the new file will be generated by concatenating the
    2039      * prefix, five or more internally-generated characters, and the suffix.
    2040      *
    2041      * <p> If the {@code directory} argument is {@code null} then the
    2042      * system-dependent default temporary-file directory will be used.  The
    2043      * default temporary-file directory is specified by the system property
    2044      * {@code java.io.tmpdir}.  On UNIX systems the default value of this
    2045      * property is typically {@code "/tmp"} or {@code "/var/tmp"}; on
    2046      * Microsoft Windows systems it is typically {@code "C:\\WINNT\\TEMP"}.  A different
    2047      * value may be given to this system property when the Java virtual machine
    2048      * is invoked, but programmatic changes to this property are not guaranteed
    2049      * to have any effect upon the temporary directory used by this method.
    2050      *
    2051      * @param  prefix     The prefix string to be used in generating the file's
    2052      *                    name; must be at least three characters long
    2053      *
    2054      * @param  suffix     The suffix string to be used in generating the file's
    2055      *                    name; may be {@code null}, in which case the
    2056      *                    suffix {@code ".tmp"} will be used
    2057      *
    2058      * @param  directory  The directory in which the file is to be created, or
    2059      *                    {@code null} if the default temporary-file
    2060      *                    directory is to be used
    2061      *
    2062      * @return  An abstract pathname denoting a newly-created empty file
    2063      *
    2064      * @throws  IllegalArgumentException
    2065      *          If the {@code prefix} argument contains fewer than three
    2066      *          characters
    2067      *
    2068      * @throws  IOException  If a file could not be created
    2069      *
    2070      * @throws  SecurityException
    2071      *          If a security manager exists and its {@link
    2072      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    2073      *          method does not allow a file to be created
    2074      *
    2075      * @since 1.2
    2076      */
    2077     public static File createTempFile(String prefix, String suffix,
    2078                                       File directory)
    2079         throws IOException
    2080     {
    2081         if (prefix.length() < 3) {
    2082             throw new IllegalArgumentException("Prefix string \"" + prefix +
    2083                 "\" too short: length must be at least 3");
    2084         }
    2085         if (suffix == null)
    2086             suffix = ".tmp";
    2087
    2088         File tmpdir = (directory != null) ? directory
    2089                                           : TempDirectory.location();
    2090         SecurityManager sm = System.getSecurityManager();
    2091         File f;
    2092         do {
    2093             f = TempDirectory.generateFile(prefix, suffix, tmpdir);
    2094
    2095             if (sm != null) {
    2096                 try {
    2097                     sm.checkWrite(f.getPath());
    2098                 } catch (SecurityException se) {
    2099                     // don't reveal temporary directory location
    2100                     if (directory == null)
    2101                         throw new SecurityException("Unable to create temporary file");
    2102                     throw se;
    2103                 }
    2104             }
    2105         } while (fs.hasBooleanAttributes(f, FileSystem.BA_EXISTS));
    2106
    2107         if (!fs.createFileExclusively(f.getPath()))
    2108             throw new IOException("Unable to create temporary file");
    2109
    2110         return f;
    2111     }
    2112
    2113     /**
    2114      * Creates an empty file in the default temporary-file directory, using
    2115      * the given prefix and suffix to generate its name. Invoking this method
    2116      * is equivalent to invoking {@link #createTempFile(java.lang.String,
    2117      * java.lang.String, java.io.File)
    2118      * createTempFile(prefix,&nbsp;suffix,&nbsp;null)}.
    2119      *
    2120      * <p> The {@link
    2121      * java.nio.file.Files#createTempFile(String,String,java.nio.file.attribute.FileAttribute[])
    2122      * Files.createTempFile} method provides an alternative method to create an
    2123      * empty file in the temporary-file directory. Files created by that method
    2124      * may have more restrictive access permissions to files created by this
    2125      * method and so may be more suited to security-sensitive applications.
    2126      *
    2127      * @param  prefix     The prefix string to be used in generating the file's
    2128      *                    name; must be at least three characters long
    2129      *
    2130      * @param  suffix     The suffix string to be used in generating the file's
    2131      *                    name; may be {@code null}, in which case the
    2132      *                    suffix {@code ".tmp"} will be used
    2133      *
    2134      * @return  An abstract pathname denoting a newly-created empty file
    2135      *
    2136      * @throws  IllegalArgumentException
    2137      *          If the {@code prefix} argument contains fewer than three
    2138      *          characters
    2139      *
    2140      * @throws  IOException  If a file could not be created
    2141      *
    2142      * @throws  SecurityException
    2143      *          If a security manager exists and its {@link
    2144      *          java.lang.SecurityManager#checkWrite(java.lang.String)}
    2145      *          method does not allow a file to be created
    2146      *
    2147      * @since 1.2
    2148      * @see java.nio.file.Files#createTempDirectory(String,FileAttribute[])
    2149      */
    2150     public static File createTempFile(String prefix, String suffix)
    2151         throws IOException
    2152     {
    2153         return createTempFile(prefix, suffix, null);
    2154     }
    2155
    2156     /* -- Basic infrastructure -- */
    2157
    2158     /**
    2159      * Compares two abstract pathnames lexicographically.  The ordering
    2160      * defined by this method depends upon the underlying system.  On UNIX
    2161      * systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows
    2162      * systems it is not.
    2163      *
    2164      * @param   pathname  The abstract pathname to be compared to this abstract
    2165      *                    pathname
    2166      *
    2167      * @return  Zero if the argument is equal to this abstract pathname, a
    2168      *          value less than zero if this abstract pathname is
    2169      *          lexicographically less than the argument, or a value greater
    2170      *          than zero if this abstract pathname is lexicographically
    2171      *          greater than the argument
    2172      *
    2173      * @since   1.2
    2174      */
    2175     public int compareTo(File pathname) {
    2176         return fs.compare(this, pathname);
    2177     }
    2178
    2179     /**
    2180      * Tests this abstract pathname for equality with the given object.
    2181      * Returns {@code true} if and only if the argument is not
    2182      * {@code null} and is an abstract pathname that denotes the same file
    2183      * or directory as this abstract pathname.  Whether or not two abstract
    2184      * pathnames are equal depends upon the underlying system.  On UNIX
    2185      * systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows
    2186      * systems it is not.
    2187      *
    2188      * @param   obj   The object to be compared with this abstract pathname
    2189      *
    2190      * @return  {@code true} if and only if the objects are the same;
    2191      *          {@code false} otherwise
    2192      */
    2193     public boolean equals(Object obj) {
    2194         if ((obj != null) && (obj instanceof File)) {
    2195             return compareTo((File)obj) == 0;
    2196         }
    2197         return false;
    2198     }
    2199
    2200     /**
    2201      * Computes a hash code for this abstract pathname.  Because equality of
    2202      * abstract pathnames is inherently system-dependent, so is the computation
    2203      * of their hash codes.  On UNIX systems, the hash code of an abstract
    2204      * pathname is equal to the exclusive <em>or</em> of the hash code
    2205      * of its pathname string and the decimal value
    2206      * {@code 1234321}.  On Microsoft Windows systems, the hash
    2207      * code is equal to the exclusive <em>or</em> of the hash code of
    2208      * its pathname string converted to lower case and the decimal
    2209      * value {@code 1234321}.  Locale is not taken into account on
    2210      * lowercasing the pathname string.
    2211      *
    2212      * @return  A hash code for this abstract pathname
    2213      */
    2214     public int hashCode() {
    2215         return fs.hashCode(this);
    2216     }
    2217
    2218     /**
    2219      * Returns the pathname string of this abstract pathname.  This is just the
    2220      * string returned by the {@link #getPath} method.
    2221      *
    2222      * @return  The string form of this abstract pathname
    2223      */
    2224     public String toString() {
    2225         return getPath();
    2226     }
    2227
    2228     /**
    2229      * WriteObject is called to save this filename.
    2230      * The separator character is saved also so it can be replaced
    2231      * in case the path is reconstituted on a different host type.
    2232      *
    2233      * @serialData  Default fields followed by separator character.
    2234      *
    2235      * @param  s the {@code ObjectOutputStream} to which data is written
    2236      * @throws IOException if an I/O error occurs
    2237      */
    2238     @java.io.Serial
    2239     private synchronized void writeObject(java.io.ObjectOutputStream s)
    2240         throws IOException
    2241     {
    2242         s.defaultWriteObject();
    2243         s.writeChar(separatorChar); // Add the separator character
    2244     }
    2245
    2246     /**
    2247      * readObject is called to restore this filename.
    2248      * The original separator character is read.  If it is different
    2249      * than the separator character on this system, then the old separator
    2250      * is replaced by the local separator.
    2251      *
    2252      * @param  s the {@code ObjectInputStream} from which data is read
    2253      * @throws IOException if an I/O error occurs
    2254      * @throws ClassNotFoundException if a serialized class cannot be loaded
    2255      */
    2256     @java.io.Serial
    2257     private synchronized void readObject(java.io.ObjectInputStream s)
    2258          throws IOException, ClassNotFoundException
    2259     {
    2260         ObjectInputStream.GetField fields = s.readFields();
    2261         String pathField = (String)fields.get("path", null);
    2262         char sep = s.readChar(); // read the previous separator char
    2263         if (sep != separatorChar)
    2264             pathField = pathField.replace(sep, separatorChar);
    2265         String path = fs.normalize(pathField);
    2266         UNSAFE.putReference(this, PATH_OFFSET, path);
    2267         UNSAFE.putIntVolatile(this, PREFIX_LENGTH_OFFSET, fs.prefixLength(path));
    2268     }
    2269
    2270     private static final jdk.internal.misc.Unsafe UNSAFE
    2271             = jdk.internal.misc.Unsafe.getUnsafe();
    2272     private static final long PATH_OFFSET
    2273             = UNSAFE.objectFieldOffset(File.class, "path");
    2274     private static final long PREFIX_LENGTH_OFFSET
    2275             = UNSAFE.objectFieldOffset(File.class, "prefixLength");
    2276
    2277     /** use serialVersionUID from JDK 1.0.2 for interoperability */
    2278     @java.io.Serial
    2279     private static final long serialVersionUID = 301077366599181567L;
    2280
    2281     // -- Integration with java.nio.file --
    2282
    2283     private transient volatile Path filePath;
    2284
    2285     /**
    2286      * Returns a {@link Path java.nio.file.Path} object constructed from
    2287      * this abstract path. The resulting {@code Path} is associated with the
    2288      * {@link java.nio.file.FileSystems#getDefault default-filesystem}.
    2289      *
    2290      * <p> The first invocation of this method works as if invoking it were
    2291      * equivalent to evaluating the expression:
    2292      * <blockquote><pre>
    2293      * {@link java.nio.file.FileSystems#getDefault FileSystems.getDefault}().{@link
    2294      * java.nio.file.FileSystem#getPath getPath}(this.{@link #getPath getPath}());
    2295      * </pre></blockquote>
    2296      * Subsequent invocations of this method return the same {@code Path}.
    2297      *
    2298      * <p> If this abstract pathname is the empty abstract pathname then this
    2299      * method returns a {@code Path} that may be used to access the current
    2300      * user directory.
    2301      *
    2302      * @return  a {@code Path} constructed from this abstract path
    2303      *
    2304      * @throws  java.nio.file.InvalidPathException
    2305      *          if a {@code Path} object cannot be constructed from the abstract
    2306      *          path (see {@link java.nio.file.FileSystem#getPath FileSystem.getPath})
    2307      *
    2308      * @since   1.7
    2309      * @see Path#toFile
    2310      */
    2311     public Path toPath() {
    2312         Path result = filePath;
    2313         if (result == null) {
    2314             synchronized (this) {
    2315                 result = filePath;
    2316                 if (result == null) {
    2317                     result = FileSystems.getDefault().getPath(path);
    2318                     filePath = result;
    2319                 }
    2320             }
    2321         }
    2322         return result;
    2323     }
    2324 }
    --- EOF ---