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