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