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