Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/io/File.java
38829 views
/*1* Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.io;2627import java.net.URI;28import java.net.URL;29import java.net.MalformedURLException;30import java.net.URISyntaxException;31import java.util.List;32import java.util.ArrayList;33import java.security.AccessController;34import java.security.SecureRandom;35import java.nio.file.Path;36import java.nio.file.FileSystems;37import sun.security.action.GetPropertyAction;3839/**40* An abstract representation of file and directory pathnames.41*42* <p> User interfaces and operating systems use system-dependent <em>pathname43* strings</em> to name files and directories. This class presents an44* abstract, system-independent view of hierarchical pathnames. An45* <em>abstract pathname</em> has two components:46*47* <ol>48* <li> An optional system-dependent <em>prefix</em> string,49* such as a disk-drive specifier, <code>"/"</code> for the UNIX root50* directory, or <code>"\\\\"</code> for a Microsoft Windows UNC pathname, and51* <li> A sequence of zero or more string <em>names</em>.52* </ol>53*54* The first name in an abstract pathname may be a directory name or, in the55* case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name56* in an abstract pathname denotes a directory; the last name may denote57* either a directory or a file. The <em>empty</em> abstract pathname has no58* prefix and an empty name sequence.59*60* <p> The conversion of a pathname string to or from an abstract pathname is61* inherently system-dependent. When an abstract pathname is converted into a62* pathname string, each name is separated from the next by a single copy of63* the default <em>separator character</em>. The default name-separator64* character is defined by the system property <code>file.separator</code>, and65* is made available in the public static fields <code>{@link66* #separator}</code> and <code>{@link #separatorChar}</code> of this class.67* When a pathname string is converted into an abstract pathname, the names68* within it may be separated by the default name-separator character or by any69* other name-separator character that is supported by the underlying system.70*71* <p> A pathname, whether abstract or in string form, may be either72* <em>absolute</em> or <em>relative</em>. An absolute pathname is complete in73* that no other information is required in order to locate the file that it74* denotes. A relative pathname, in contrast, must be interpreted in terms of75* information taken from some other pathname. By default the classes in the76* <code>java.io</code> package always resolve relative pathnames against the77* current user directory. This directory is named by the system property78* <code>user.dir</code>, and is typically the directory in which the Java79* virtual machine was invoked.80*81* <p> The <em>parent</em> of an abstract pathname may be obtained by invoking82* the {@link #getParent} method of this class and consists of the pathname's83* prefix and each name in the pathname's name sequence except for the last.84* Each directory's absolute pathname is an ancestor of any <tt>File</tt>85* object with an absolute abstract pathname which begins with the directory's86* absolute pathname. For example, the directory denoted by the abstract87* pathname <tt>"/usr"</tt> is an ancestor of the directory denoted by the88* pathname <tt>"/usr/local/bin"</tt>.89*90* <p> The prefix concept is used to handle root directories on UNIX platforms,91* and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms,92* as follows:93*94* <ul>95*96* <li> For UNIX platforms, the prefix of an absolute pathname is always97* <code>"/"</code>. Relative pathnames have no prefix. The abstract pathname98* denoting the root directory has the prefix <code>"/"</code> and an empty99* name sequence.100*101* <li> For Microsoft Windows platforms, the prefix of a pathname that contains a drive102* specifier consists of the drive letter followed by <code>":"</code> and103* possibly followed by <code>"\\"</code> if the pathname is absolute. The104* prefix of a UNC pathname is <code>"\\\\"</code>; the hostname and the share105* name are the first two names in the name sequence. A relative pathname that106* does not specify a drive has no prefix.107*108* </ul>109*110* <p> Instances of this class may or may not denote an actual file-system111* object such as a file or a directory. If it does denote such an object112* then that object resides in a <i>partition</i>. A partition is an113* operating system-specific portion of storage for a file system. A single114* storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may115* contain multiple partitions. The object, if any, will reside on the116* partition <a name="partName">named</a> by some ancestor of the absolute117* form of this pathname.118*119* <p> A file system may implement restrictions to certain operations on the120* actual file-system object, such as reading, writing, and executing. These121* restrictions are collectively known as <i>access permissions</i>. The file122* system may have multiple sets of access permissions on a single object.123* For example, one set may apply to the object's <i>owner</i>, and another124* may apply to all other users. The access permissions on an object may125* cause some methods in this class to fail.126*127* <p> Instances of the <code>File</code> class are immutable; that is, once128* created, the abstract pathname represented by a <code>File</code> object129* will never change.130*131* <h3>Interoperability with {@code java.nio.file} package</h3>132*133* <p> The <a href="../../java/nio/file/package-summary.html">{@code java.nio.file}</a>134* package defines interfaces and classes for the Java virtual machine to access135* files, file attributes, and file systems. This API may be used to overcome136* many of the limitations of the {@code java.io.File} class.137* The {@link #toPath toPath} method may be used to obtain a {@link138* Path} that uses the abstract path represented by a {@code File} object to139* locate a file. The resulting {@code Path} may be used with the {@link140* java.nio.file.Files} class to provide more efficient and extensive access to141* additional file operations, file attributes, and I/O exceptions to help142* diagnose errors when an operation on a file fails.143*144* @author unascribed145* @since JDK1.0146*/147148public class File149implements Serializable, Comparable<File>150{151152/**153* The FileSystem object representing the platform's local file system.154*/155private static final FileSystem fs = DefaultFileSystem.getFileSystem();156157/**158* This abstract pathname's normalized pathname string. A normalized159* pathname string uses the default name-separator character and does not160* contain any duplicate or redundant separators.161*162* @serial163*/164private final String path;165166/**167* Enum type that indicates the status of a file path.168*/169private static enum PathStatus { INVALID, CHECKED };170171/**172* The flag indicating whether the file path is invalid.173*/174private transient PathStatus status = null;175176/**177* Check if the file has an invalid path. Currently, the inspection of178* a file path is very limited, and it only covers Nul character check.179* Returning true means the path is definitely invalid/garbage. But180* returning false does not guarantee that the path is valid.181*182* @return true if the file path is invalid.183*/184final boolean isInvalid() {185PathStatus s = status;186if (s == null) {187s = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED188: PathStatus.INVALID;189status = s;190}191return s == PathStatus.INVALID;192}193194/**195* The length of this abstract pathname's prefix, or zero if it has no196* prefix.197*/198private final transient int prefixLength;199200/**201* Returns the length of this abstract pathname's prefix.202* For use by FileSystem classes.203*/204int getPrefixLength() {205return prefixLength;206}207208/**209* The system-dependent default name-separator character. This field is210* initialized to contain the first character of the value of the system211* property <code>file.separator</code>. On UNIX systems the value of this212* field is <code>'/'</code>; on Microsoft Windows systems it is <code>'\\'</code>.213*214* @see java.lang.System#getProperty(java.lang.String)215*/216public static final char separatorChar = fs.getSeparator();217218/**219* The system-dependent default name-separator character, represented as a220* string for convenience. This string contains a single character, namely221* <code>{@link #separatorChar}</code>.222*/223public static final String separator = "" + separatorChar;224225/**226* The system-dependent path-separator character. This field is227* initialized to contain the first character of the value of the system228* property <code>path.separator</code>. This character is used to229* separate filenames in a sequence of files given as a <em>path list</em>.230* On UNIX systems, this character is <code>':'</code>; on Microsoft Windows systems it231* is <code>';'</code>.232*233* @see java.lang.System#getProperty(java.lang.String)234*/235public static final char pathSeparatorChar = fs.getPathSeparator();236237/**238* The system-dependent path-separator character, represented as a string239* for convenience. This string contains a single character, namely240* <code>{@link #pathSeparatorChar}</code>.241*/242public static final String pathSeparator = "" + pathSeparatorChar;243244245/* -- Constructors -- */246247/**248* Internal constructor for already-normalized pathname strings.249*/250private File(String pathname, int prefixLength) {251this.path = pathname;252this.prefixLength = prefixLength;253}254255/**256* Internal constructor for already-normalized pathname strings.257* The parameter order is used to disambiguate this method from the258* public(File, String) constructor.259*/260private File(String child, File parent) {261assert parent.path != null;262assert (!parent.path.equals(""));263this.path = fs.resolve(parent.path, child);264this.prefixLength = parent.prefixLength;265}266267/**268* Creates a new <code>File</code> instance by converting the given269* pathname string into an abstract pathname. If the given string is270* the empty string, then the result is the empty abstract pathname.271*272* @param pathname A pathname string273* @throws NullPointerException274* If the <code>pathname</code> argument is <code>null</code>275*/276public File(String pathname) {277if (pathname == null) {278throw new NullPointerException();279}280this.path = fs.normalize(pathname);281this.prefixLength = fs.prefixLength(this.path);282}283284/* Note: The two-argument File constructors do not interpret an empty285parent abstract pathname as the current user directory. An empty parent286instead causes the child to be resolved against the system-dependent287directory defined by the FileSystem.getDefaultParent method. On Unix288this default is "/", while on Microsoft Windows it is "\\". This is required for289compatibility with the original behavior of this class. */290291/**292* Creates a new <code>File</code> instance from a parent pathname string293* and a child pathname string.294*295* <p> If <code>parent</code> is <code>null</code> then the new296* <code>File</code> instance is created as if by invoking the297* single-argument <code>File</code> constructor on the given298* <code>child</code> pathname string.299*300* <p> Otherwise the <code>parent</code> pathname string is taken to denote301* a directory, and the <code>child</code> pathname string is taken to302* denote either a directory or a file. If the <code>child</code> pathname303* string is absolute then it is converted into a relative pathname in a304* system-dependent way. If <code>parent</code> is the empty string then305* the new <code>File</code> instance is created by converting306* <code>child</code> into an abstract pathname and resolving the result307* against a system-dependent default directory. Otherwise each pathname308* string is converted into an abstract pathname and the child abstract309* pathname is resolved against the parent.310*311* @param parent The parent pathname string312* @param child The child pathname string313* @throws NullPointerException314* If <code>child</code> is <code>null</code>315*/316public File(String parent, String child) {317if (child == null) {318throw new NullPointerException();319}320if (parent != null) {321if (parent.equals("")) {322this.path = fs.resolve(fs.getDefaultParent(),323fs.normalize(child));324} else {325this.path = fs.resolve(fs.normalize(parent),326fs.normalize(child));327}328} else {329this.path = fs.normalize(child);330}331this.prefixLength = fs.prefixLength(this.path);332}333334/**335* Creates a new <code>File</code> instance from a parent abstract336* pathname and a child pathname string.337*338* <p> If <code>parent</code> is <code>null</code> then the new339* <code>File</code> instance is created as if by invoking the340* single-argument <code>File</code> constructor on the given341* <code>child</code> pathname string.342*343* <p> Otherwise the <code>parent</code> abstract pathname is taken to344* denote a directory, and the <code>child</code> pathname string is taken345* to denote either a directory or a file. If the <code>child</code>346* pathname string is absolute then it is converted into a relative347* pathname in a system-dependent way. If <code>parent</code> is the empty348* abstract pathname then the new <code>File</code> instance is created by349* converting <code>child</code> into an abstract pathname and resolving350* the result against a system-dependent default directory. Otherwise each351* pathname string is converted into an abstract pathname and the child352* abstract pathname is resolved against the parent.353*354* @param parent The parent abstract pathname355* @param child The child pathname string356* @throws NullPointerException357* If <code>child</code> is <code>null</code>358*/359public File(File parent, String child) {360if (child == null) {361throw new NullPointerException();362}363if (parent != null) {364if (parent.path.equals("")) {365this.path = fs.resolve(fs.getDefaultParent(),366fs.normalize(child));367} else {368this.path = fs.resolve(parent.path,369fs.normalize(child));370}371} else {372this.path = fs.normalize(child);373}374this.prefixLength = fs.prefixLength(this.path);375}376377/**378* Creates a new <tt>File</tt> instance by converting the given379* <tt>file:</tt> URI into an abstract pathname.380*381* <p> The exact form of a <tt>file:</tt> URI is system-dependent, hence382* the transformation performed by this constructor is also383* system-dependent.384*385* <p> For a given abstract pathname <i>f</i> it is guaranteed that386*387* <blockquote><tt>388* new File(</tt><i> f</i><tt>.{@link #toURI() toURI}()).equals(</tt><i> f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}())389* </tt></blockquote>390*391* so long as the original abstract pathname, the URI, and the new abstract392* pathname are all created in (possibly different invocations of) the same393* Java virtual machine. This relationship typically does not hold,394* however, when a <tt>file:</tt> URI that is created in a virtual machine395* on one operating system is converted into an abstract pathname in a396* virtual machine on a different operating system.397*398* @param uri399* An absolute, hierarchical URI with a scheme equal to400* <tt>"file"</tt>, a non-empty path component, and undefined401* authority, query, and fragment components402*403* @throws NullPointerException404* If <tt>uri</tt> is <tt>null</tt>405*406* @throws IllegalArgumentException407* If the preconditions on the parameter do not hold408*409* @see #toURI()410* @see java.net.URI411* @since 1.4412*/413public File(URI uri) {414415// Check our many preconditions416if (!uri.isAbsolute())417throw new IllegalArgumentException("URI is not absolute");418if (uri.isOpaque())419throw new IllegalArgumentException("URI is not hierarchical");420String scheme = uri.getScheme();421if ((scheme == null) || !scheme.equalsIgnoreCase("file"))422throw new IllegalArgumentException("URI scheme is not \"file\"");423if (uri.getAuthority() != null)424throw new IllegalArgumentException("URI has an authority component");425if (uri.getFragment() != null)426throw new IllegalArgumentException("URI has a fragment component");427if (uri.getQuery() != null)428throw new IllegalArgumentException("URI has a query component");429String p = uri.getPath();430if (p.equals(""))431throw new IllegalArgumentException("URI path component is empty");432433// Okay, now initialize434p = fs.fromURIPath(p);435if (File.separatorChar != '/')436p = p.replace('/', File.separatorChar);437this.path = fs.normalize(p);438this.prefixLength = fs.prefixLength(this.path);439}440441442/* -- Path-component accessors -- */443444/**445* Returns the name of the file or directory denoted by this abstract446* pathname. This is just the last name in the pathname's name447* sequence. If the pathname's name sequence is empty, then the empty448* string is returned.449*450* @return The name of the file or directory denoted by this abstract451* pathname, or the empty string if this pathname's name sequence452* is empty453*/454public String getName() {455int index = path.lastIndexOf(separatorChar);456if (index < prefixLength) return path.substring(prefixLength);457return path.substring(index + 1);458}459460/**461* Returns the pathname string of this abstract pathname's parent, or462* <code>null</code> if this pathname does not name a parent directory.463*464* <p> The <em>parent</em> of an abstract pathname consists of the465* pathname's prefix, if any, and each name in the pathname's name466* sequence except for the last. If the name sequence is empty then467* the pathname does not name a parent directory.468*469* @return The pathname string of the parent directory named by this470* abstract pathname, or <code>null</code> if this pathname471* does not name a parent472*/473public String getParent() {474int index = path.lastIndexOf(separatorChar);475if (index < prefixLength) {476if ((prefixLength > 0) && (path.length() > prefixLength))477return path.substring(0, prefixLength);478return null;479}480return path.substring(0, index);481}482483/**484* Returns the abstract pathname of this abstract pathname's parent,485* or <code>null</code> if this pathname does not name a parent486* directory.487*488* <p> The <em>parent</em> of an abstract pathname consists of the489* pathname's prefix, if any, and each name in the pathname's name490* sequence except for the last. If the name sequence is empty then491* the pathname does not name a parent directory.492*493* @return The abstract pathname of the parent directory named by this494* abstract pathname, or <code>null</code> if this pathname495* does not name a parent496*497* @since 1.2498*/499public File getParentFile() {500String p = this.getParent();501if (p == null) return null;502if (getClass() != File.class) {503p = fs.normalize(p);504}505return new File(p, this.prefixLength);506}507508/**509* Converts this abstract pathname into a pathname string. The resulting510* string uses the {@link #separator default name-separator character} to511* separate the names in the name sequence.512*513* @return The string form of this abstract pathname514*/515public String getPath() {516return path;517}518519520/* -- Path operations -- */521522/**523* Tests whether this abstract pathname is absolute. The definition of524* absolute pathname is system dependent. On UNIX systems, a pathname is525* absolute if its prefix is <code>"/"</code>. On Microsoft Windows systems, a526* pathname is absolute if its prefix is a drive specifier followed by527* <code>"\\"</code>, or if its prefix is <code>"\\\\"</code>.528*529* @return <code>true</code> if this abstract pathname is absolute,530* <code>false</code> otherwise531*/532public boolean isAbsolute() {533return fs.isAbsolute(this);534}535536/**537* Returns the absolute pathname string of this abstract pathname.538*539* <p> If this abstract pathname is already absolute, then the pathname540* string is simply returned as if by the <code>{@link #getPath}</code>541* method. If this abstract pathname is the empty abstract pathname then542* the pathname string of the current user directory, which is named by the543* system property <code>user.dir</code>, is returned. Otherwise this544* pathname is resolved in a system-dependent way. On UNIX systems, a545* relative pathname is made absolute by resolving it against the current546* user directory. On Microsoft Windows systems, a relative pathname is made absolute547* by resolving it against the current directory of the drive named by the548* pathname, if any; if not, it is resolved against the current user549* directory.550*551* @return The absolute pathname string denoting the same file or552* directory as this abstract pathname553*554* @throws SecurityException555* If a required system property value cannot be accessed.556*557* @see java.io.File#isAbsolute()558*/559public String getAbsolutePath() {560return fs.resolve(this);561}562563/**564* Returns the absolute form of this abstract pathname. Equivalent to565* <code>new File(this.{@link #getAbsolutePath})</code>.566*567* @return The absolute abstract pathname denoting the same file or568* directory as this abstract pathname569*570* @throws SecurityException571* If a required system property value cannot be accessed.572*573* @since 1.2574*/575public File getAbsoluteFile() {576String absPath = getAbsolutePath();577if (getClass() != File.class) {578absPath = fs.normalize(absPath);579}580return new File(absPath, fs.prefixLength(absPath));581}582583/**584* Returns the canonical pathname string of this abstract pathname.585*586* <p> A canonical pathname is both absolute and unique. The precise587* definition of canonical form is system-dependent. This method first588* converts this pathname to absolute form if necessary, as if by invoking the589* {@link #getAbsolutePath} method, and then maps it to its unique form in a590* system-dependent way. This typically involves removing redundant names591* such as <tt>"."</tt> and <tt>".."</tt> from the pathname, resolving592* symbolic links (on UNIX platforms), and converting drive letters to a593* standard case (on Microsoft Windows platforms).594*595* <p> Every pathname that denotes an existing file or directory has a596* unique canonical form. Every pathname that denotes a nonexistent file597* or directory also has a unique canonical form. The canonical form of598* the pathname of a nonexistent file or directory may be different from599* the canonical form of the same pathname after the file or directory is600* created. Similarly, the canonical form of the pathname of an existing601* file or directory may be different from the canonical form of the same602* pathname after the file or directory is deleted.603*604* @return The canonical pathname string denoting the same file or605* directory as this abstract pathname606*607* @throws IOException608* If an I/O error occurs, which is possible because the609* construction of the canonical pathname may require610* filesystem queries611*612* @throws SecurityException613* If a required system property value cannot be accessed, or614* if a security manager exists and its <code>{@link615* java.lang.SecurityManager#checkRead}</code> method denies616* read access to the file617*618* @since JDK1.1619* @see Path#toRealPath620*/621public String getCanonicalPath() throws IOException {622if (isInvalid()) {623throw new IOException("Invalid file path");624}625return fs.canonicalize(fs.resolve(this));626}627628/**629* Returns the canonical form of this abstract pathname. Equivalent to630* <code>new File(this.{@link #getCanonicalPath})</code>.631*632* @return The canonical pathname string denoting the same file or633* directory as this abstract pathname634*635* @throws IOException636* If an I/O error occurs, which is possible because the637* construction of the canonical pathname may require638* filesystem queries639*640* @throws SecurityException641* If a required system property value cannot be accessed, or642* if a security manager exists and its <code>{@link643* java.lang.SecurityManager#checkRead}</code> method denies644* read access to the file645*646* @since 1.2647* @see Path#toRealPath648*/649public File getCanonicalFile() throws IOException {650String canonPath = getCanonicalPath();651if (getClass() != File.class) {652canonPath = fs.normalize(canonPath);653}654return new File(canonPath, fs.prefixLength(canonPath));655}656657private static String slashify(String path, boolean isDirectory) {658String p = path;659if (File.separatorChar != '/')660p = p.replace(File.separatorChar, '/');661if (!p.startsWith("/"))662p = "/" + p;663if (!p.endsWith("/") && isDirectory)664p = p + "/";665return p;666}667668/**669* Converts this abstract pathname into a <code>file:</code> URL. The670* exact form of the URL is system-dependent. If it can be determined that671* the file denoted by this abstract pathname is a directory, then the672* resulting URL will end with a slash.673*674* @return A URL object representing the equivalent file URL675*676* @throws MalformedURLException677* If the path cannot be parsed as a URL678*679* @see #toURI()680* @see java.net.URI681* @see java.net.URI#toURL()682* @see java.net.URL683* @since 1.2684*685* @deprecated This method does not automatically escape characters that686* are illegal in URLs. It is recommended that new code convert an687* abstract pathname into a URL by first converting it into a URI, via the688* {@link #toURI() toURI} method, and then converting the URI into a URL689* via the {@link java.net.URI#toURL() URI.toURL} method.690*/691@Deprecated692public URL toURL() throws MalformedURLException {693if (isInvalid()) {694throw new MalformedURLException("Invalid file path");695}696return new URL("file", "", slashify(getAbsolutePath(), isDirectory()));697}698699/**700* Constructs a <tt>file:</tt> URI that represents this abstract pathname.701*702* <p> The exact form of the URI is system-dependent. If it can be703* determined that the file denoted by this abstract pathname is a704* directory, then the resulting URI will end with a slash.705*706* <p> For a given abstract pathname <i>f</i>, it is guaranteed that707*708* <blockquote><tt>709* new {@link #File(java.net.URI) File}(</tt><i> f</i><tt>.toURI()).equals(</tt><i> f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}())710* </tt></blockquote>711*712* so long as the original abstract pathname, the URI, and the new abstract713* pathname are all created in (possibly different invocations of) the same714* Java virtual machine. Due to the system-dependent nature of abstract715* pathnames, however, this relationship typically does not hold when a716* <tt>file:</tt> URI that is created in a virtual machine on one operating717* system is converted into an abstract pathname in a virtual machine on a718* different operating system.719*720* <p> Note that when this abstract pathname represents a UNC pathname then721* all components of the UNC (including the server name component) are encoded722* in the {@code URI} path. The authority component is undefined, meaning723* that it is represented as {@code null}. The {@link Path} class defines the724* {@link Path#toUri toUri} method to encode the server name in the authority725* component of the resulting {@code URI}. The {@link #toPath toPath} method726* may be used to obtain a {@code Path} representing this abstract pathname.727*728* @return An absolute, hierarchical URI with a scheme equal to729* <tt>"file"</tt>, a path representing this abstract pathname,730* and undefined authority, query, and fragment components731* @throws SecurityException If a required system property value cannot732* be accessed.733*734* @see #File(java.net.URI)735* @see java.net.URI736* @see java.net.URI#toURL()737* @since 1.4738*/739public URI toURI() {740try {741File f = getAbsoluteFile();742String sp = slashify(f.getPath(), f.isDirectory());743if (sp.startsWith("//"))744sp = "//" + sp;745return new URI("file", null, sp, null);746} catch (URISyntaxException x) {747throw new Error(x); // Can't happen748}749}750751752/* -- Attribute accessors -- */753754/**755* Tests whether the application can read the file denoted by this756* abstract pathname. On some platforms it may be possible to start the757* Java virtual machine with special privileges that allow it to read758* files that are marked as unreadable. Consequently this method may return759* {@code true} even though the file does not have read permissions.760*761* @return <code>true</code> if and only if the file specified by this762* abstract pathname exists <em>and</em> can be read by the763* application; <code>false</code> otherwise764*765* @throws SecurityException766* If a security manager exists and its <code>{@link767* java.lang.SecurityManager#checkRead(java.lang.String)}</code>768* method denies read access to the file769*/770public boolean canRead() {771SecurityManager security = System.getSecurityManager();772if (security != null) {773security.checkRead(path);774}775if (isInvalid()) {776return false;777}778return fs.checkAccess(this, FileSystem.ACCESS_READ);779}780781/**782* Tests whether the application can modify the file denoted by this783* abstract pathname. On some platforms it may be possible to start the784* Java virtual machine with special privileges that allow it to modify785* files that are marked read-only. Consequently this method may return786* {@code true} even though the file is marked read-only.787*788* @return <code>true</code> if and only if the file system actually789* contains a file denoted by this abstract pathname <em>and</em>790* the application is allowed to write to the file;791* <code>false</code> otherwise.792*793* @throws SecurityException794* If a security manager exists and its <code>{@link795* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>796* method denies write access to the file797*/798public boolean canWrite() {799SecurityManager security = System.getSecurityManager();800if (security != null) {801security.checkWrite(path);802}803if (isInvalid()) {804return false;805}806return fs.checkAccess(this, FileSystem.ACCESS_WRITE);807}808809/**810* Tests whether the file or directory denoted by this abstract pathname811* exists.812*813* @return <code>true</code> if and only if the file or directory denoted814* by this abstract pathname exists; <code>false</code> otherwise815*816* @throws SecurityException817* If a security manager exists and its <code>{@link818* java.lang.SecurityManager#checkRead(java.lang.String)}</code>819* method denies read access to the file or directory820*/821public boolean exists() {822SecurityManager security = System.getSecurityManager();823if (security != null) {824security.checkRead(path);825}826if (isInvalid()) {827return false;828}829return ((fs.getBooleanAttributes(this) & FileSystem.BA_EXISTS) != 0);830}831832/**833* Tests whether the file denoted by this abstract pathname is a834* directory.835*836* <p> Where it is required to distinguish an I/O exception from the case837* that the file is not a directory, or where several attributes of the838* same file are required at the same time, then the {@link839* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])840* Files.readAttributes} method may be used.841*842* @return <code>true</code> if and only if the file denoted by this843* abstract pathname exists <em>and</em> is a directory;844* <code>false</code> otherwise845*846* @throws SecurityException847* If a security manager exists and its <code>{@link848* java.lang.SecurityManager#checkRead(java.lang.String)}</code>849* method denies read access to the file850*/851public boolean isDirectory() {852SecurityManager security = System.getSecurityManager();853if (security != null) {854security.checkRead(path);855}856if (isInvalid()) {857return false;858}859return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY)860!= 0);861}862863/**864* Tests whether the file denoted by this abstract pathname is a normal865* file. A file is <em>normal</em> if it is not a directory and, in866* addition, satisfies other system-dependent criteria. Any non-directory867* file created by a Java application is guaranteed to be a normal file.868*869* <p> Where it is required to distinguish an I/O exception from the case870* that the file is not a normal file, or where several attributes of the871* same file are required at the same time, then the {@link872* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])873* Files.readAttributes} method may be used.874*875* @return <code>true</code> if and only if the file denoted by this876* abstract pathname exists <em>and</em> is a normal file;877* <code>false</code> otherwise878*879* @throws SecurityException880* If a security manager exists and its <code>{@link881* java.lang.SecurityManager#checkRead(java.lang.String)}</code>882* method denies read access to the file883*/884public boolean isFile() {885SecurityManager security = System.getSecurityManager();886if (security != null) {887security.checkRead(path);888}889if (isInvalid()) {890return false;891}892return ((fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0);893}894895/**896* Tests whether the file named by this abstract pathname is a hidden897* file. The exact definition of <em>hidden</em> is system-dependent. On898* UNIX systems, a file is considered to be hidden if its name begins with899* a period character (<code>'.'</code>). On Microsoft Windows systems, a file is900* considered to be hidden if it has been marked as such in the filesystem.901*902* @return <code>true</code> if and only if the file denoted by this903* abstract pathname is hidden according to the conventions of the904* underlying platform905*906* @throws SecurityException907* If a security manager exists and its <code>{@link908* java.lang.SecurityManager#checkRead(java.lang.String)}</code>909* method denies read access to the file910*911* @since 1.2912*/913public boolean isHidden() {914SecurityManager security = System.getSecurityManager();915if (security != null) {916security.checkRead(path);917}918if (isInvalid()) {919return false;920}921return ((fs.getBooleanAttributes(this) & FileSystem.BA_HIDDEN) != 0);922}923924/**925* Returns the time that the file denoted by this abstract pathname was926* last modified.927*928* <p> Where it is required to distinguish an I/O exception from the case929* where {@code 0L} is returned, or where several attributes of the930* same file are required at the same time, or where the time of last931* access or the creation time are required, then the {@link932* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])933* Files.readAttributes} method may be used.934*935* @return A <code>long</code> value representing the time the file was936* last modified, measured in milliseconds since the epoch937* (00:00:00 GMT, January 1, 1970), or <code>0L</code> if the938* file does not exist or if an I/O error occurs939*940* @throws SecurityException941* If a security manager exists and its <code>{@link942* java.lang.SecurityManager#checkRead(java.lang.String)}</code>943* method denies read access to the file944*/945public long lastModified() {946SecurityManager security = System.getSecurityManager();947if (security != null) {948security.checkRead(path);949}950if (isInvalid()) {951return 0L;952}953return fs.getLastModifiedTime(this);954}955956/**957* Returns the length of the file denoted by this abstract pathname.958* The return value is unspecified if this pathname denotes a directory.959*960* <p> Where it is required to distinguish an I/O exception from the case961* that {@code 0L} is returned, or where several attributes of the same file962* are required at the same time, then the {@link963* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])964* Files.readAttributes} method may be used.965*966* @return The length, in bytes, of the file denoted by this abstract967* pathname, or <code>0L</code> if the file does not exist. Some968* operating systems may return <code>0L</code> for pathnames969* denoting system-dependent entities such as devices or pipes.970*971* @throws SecurityException972* If a security manager exists and its <code>{@link973* java.lang.SecurityManager#checkRead(java.lang.String)}</code>974* method denies read access to the file975*/976public long length() {977SecurityManager security = System.getSecurityManager();978if (security != null) {979security.checkRead(path);980}981if (isInvalid()) {982return 0L;983}984return fs.getLength(this);985}986987988/* -- File operations -- */989990/**991* Atomically creates a new, empty file named by this abstract pathname if992* and only if a file with this name does not yet exist. The check for the993* existence of the file and the creation of the file if it does not exist994* are a single operation that is atomic with respect to all other995* filesystem activities that might affect the file.996* <P>997* Note: this method should <i>not</i> be used for file-locking, as998* the resulting protocol cannot be made to work reliably. The999* {@link java.nio.channels.FileLock FileLock}1000* facility should be used instead.1001*1002* @return <code>true</code> if the named file does not exist and was1003* successfully created; <code>false</code> if the named file1004* already exists1005*1006* @throws IOException1007* If an I/O error occurred1008*1009* @throws SecurityException1010* If a security manager exists and its <code>{@link1011* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1012* method denies write access to the file1013*1014* @since 1.21015*/1016public boolean createNewFile() throws IOException {1017SecurityManager security = System.getSecurityManager();1018if (security != null) security.checkWrite(path);1019if (isInvalid()) {1020throw new IOException("Invalid file path");1021}1022return fs.createFileExclusively(path);1023}10241025/**1026* Deletes the file or directory denoted by this abstract pathname. If1027* this pathname denotes a directory, then the directory must be empty in1028* order to be deleted.1029*1030* <p> Note that the {@link java.nio.file.Files} class defines the {@link1031* java.nio.file.Files#delete(Path) delete} method to throw an {@link IOException}1032* when a file cannot be deleted. This is useful for error reporting and to1033* diagnose why a file cannot be deleted.1034*1035* @return <code>true</code> if and only if the file or directory is1036* successfully deleted; <code>false</code> otherwise1037*1038* @throws SecurityException1039* If a security manager exists and its <code>{@link1040* java.lang.SecurityManager#checkDelete}</code> method denies1041* delete access to the file1042*/1043public boolean delete() {1044SecurityManager security = System.getSecurityManager();1045if (security != null) {1046security.checkDelete(path);1047}1048if (isInvalid()) {1049return false;1050}1051return fs.delete(this);1052}10531054/**1055* Requests that the file or directory denoted by this abstract1056* pathname be deleted when the virtual machine terminates.1057* Files (or directories) are deleted in the reverse order that1058* they are registered. Invoking this method to delete a file or1059* directory that is already registered for deletion has no effect.1060* Deletion will be attempted only for normal termination of the1061* virtual machine, as defined by the Java Language Specification.1062*1063* <p> Once deletion has been requested, it is not possible to cancel the1064* request. This method should therefore be used with care.1065*1066* <P>1067* Note: this method should <i>not</i> be used for file-locking, as1068* the resulting protocol cannot be made to work reliably. The1069* {@link java.nio.channels.FileLock FileLock}1070* facility should be used instead.1071*1072* @throws SecurityException1073* If a security manager exists and its <code>{@link1074* java.lang.SecurityManager#checkDelete}</code> method denies1075* delete access to the file1076*1077* @see #delete1078*1079* @since 1.21080*/1081public void deleteOnExit() {1082SecurityManager security = System.getSecurityManager();1083if (security != null) {1084security.checkDelete(path);1085}1086if (isInvalid()) {1087return;1088}1089DeleteOnExitHook.add(path);1090}10911092/**1093* Returns an array of strings naming the files and directories in the1094* directory denoted by this abstract pathname.1095*1096* <p> If this abstract pathname does not denote a directory, then this1097* method returns {@code null}. Otherwise an array of strings is1098* returned, one for each file or directory in the directory. Names1099* denoting the directory itself and the directory's parent directory are1100* not included in the result. Each string is a file name rather than a1101* complete path.1102*1103* <p> There is no guarantee that the name strings in the resulting array1104* will appear in any specific order; they are not, in particular,1105* guaranteed to appear in alphabetical order.1106*1107* <p> Note that the {@link java.nio.file.Files} class defines the {@link1108* java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method to1109* open a directory and iterate over the names of the files in the directory.1110* This may use less resources when working with very large directories, and1111* may be more responsive when working with remote directories.1112*1113* @return An array of strings naming the files and directories in the1114* directory denoted by this abstract pathname. The array will be1115* empty if the directory is empty. Returns {@code null} if1116* this abstract pathname does not denote a directory, or if an1117* I/O error occurs.1118*1119* @throws SecurityException1120* If a security manager exists and its {@link1121* SecurityManager#checkRead(String)} method denies read access to1122* the directory1123*/1124public String[] list() {1125return normalizedList();1126}11271128/**1129* Returns an array of strings naming the files and directories in the1130* directory denoted by this abstract pathname. The strings are1131* ensured to represent normalized paths.1132*1133* @return An array of strings naming the files and directories in the1134* directory denoted by this abstract pathname. The array will be1135* empty if the directory is empty. Returns {@code null} if1136* this abstract pathname does not denote a directory, or if an1137* I/O error occurs.1138*1139* @throws SecurityException1140* If a security manager exists and its {@link1141* SecurityManager#checkRead(String)} method denies read access to1142* the directory1143*/1144private final String[] normalizedList() {1145SecurityManager security = System.getSecurityManager();1146if (security != null) {1147security.checkRead(path);1148}1149if (isInvalid()) {1150return null;1151}1152String[] s = fs.list(this);1153if (s != null && getClass() != File.class) {1154String[] normalized = new String[s.length];1155for (int i = 0; i < s.length; i++) {1156normalized[i] = fs.normalize(s[i]);1157}1158s = normalized;1159}1160return s;1161}11621163/**1164* Returns an array of strings naming the files and directories in the1165* directory denoted by this abstract pathname that satisfy the specified1166* filter. The behavior of this method is the same as that of the1167* {@link #list()} method, except that the strings in the returned array1168* must satisfy the filter. If the given {@code filter} is {@code null}1169* then all names are accepted. Otherwise, a name satisfies the filter if1170* and only if the value {@code true} results when the {@link1171* FilenameFilter#accept FilenameFilter.accept(File, String)} method1172* of the filter is invoked on this abstract pathname and the name of a1173* file or directory in the directory that it denotes.1174*1175* @param filter1176* A filename filter1177*1178* @return An array of strings naming the files and directories in the1179* directory denoted by this abstract pathname that were accepted1180* by the given {@code filter}. The array will be empty if the1181* directory is empty or if no names were accepted by the filter.1182* Returns {@code null} if this abstract pathname does not denote1183* a directory, or if an I/O error occurs.1184*1185* @throws SecurityException1186* If a security manager exists and its {@link1187* SecurityManager#checkRead(String)} method denies read access to1188* the directory1189*1190* @see java.nio.file.Files#newDirectoryStream(Path,String)1191*/1192public String[] list(FilenameFilter filter) {1193String names[] = normalizedList();1194if ((names == null) || (filter == null)) {1195return names;1196}1197List<String> v = new ArrayList<>();1198for (int i = 0 ; i < names.length ; i++) {1199if (filter.accept(this, names[i])) {1200v.add(names[i]);1201}1202}1203return v.toArray(new String[v.size()]);1204}12051206/**1207* Returns an array of abstract pathnames denoting the files in the1208* directory denoted by this abstract pathname.1209*1210* <p> If this abstract pathname does not denote a directory, then this1211* method returns {@code null}. Otherwise an array of {@code File} objects1212* is returned, one for each file or directory in the directory. Pathnames1213* denoting the directory itself and the directory's parent directory are1214* not included in the result. Each resulting abstract pathname is1215* constructed from this abstract pathname using the {@link #File(File,1216* String) File(File, String)} constructor. Therefore if this1217* pathname is absolute then each resulting pathname is absolute; if this1218* pathname is relative then each resulting pathname will be relative to1219* the same directory.1220*1221* <p> There is no guarantee that the name strings in the resulting array1222* will appear in any specific order; they are not, in particular,1223* guaranteed to appear in alphabetical order.1224*1225* <p> Note that the {@link java.nio.file.Files} class defines the {@link1226* java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method1227* to open a directory and iterate over the names of the files in the1228* directory. This may use less resources when working with very large1229* directories.1230*1231* @return An array of abstract pathnames denoting the files and1232* directories in the directory denoted by this abstract pathname.1233* The array will be empty if the directory is empty. Returns1234* {@code null} if this abstract pathname does not denote a1235* directory, or if an I/O error occurs.1236*1237* @throws SecurityException1238* If a security manager exists and its {@link1239* SecurityManager#checkRead(String)} method denies read access to1240* the directory1241*1242* @since 1.21243*/1244public File[] listFiles() {1245String[] ss = normalizedList();1246if (ss == null) return null;1247int n = ss.length;1248File[] fs = new File[n];1249for (int i = 0; i < n; i++) {1250fs[i] = new File(ss[i], this);1251}1252return fs;1253}12541255/**1256* Returns an array of abstract pathnames denoting the files and1257* directories in the directory denoted by this abstract pathname that1258* satisfy the specified filter. The behavior of this method is the same1259* as that of the {@link #listFiles()} method, except that the pathnames in1260* the returned array must satisfy the filter. If the given {@code filter}1261* is {@code null} then all pathnames are accepted. Otherwise, a pathname1262* satisfies the filter if and only if the value {@code true} results when1263* the {@link FilenameFilter#accept1264* FilenameFilter.accept(File, String)} method of the filter is1265* invoked on this abstract pathname and the name of a file or directory in1266* the directory that it denotes.1267*1268* @param filter1269* A filename filter1270*1271* @return An array of abstract pathnames denoting the files and1272* directories in the directory denoted by this abstract pathname.1273* The array will be empty if the directory is empty. Returns1274* {@code null} if this abstract pathname does not denote a1275* directory, or if an I/O error occurs.1276*1277* @throws SecurityException1278* If a security manager exists and its {@link1279* SecurityManager#checkRead(String)} method denies read access to1280* the directory1281*1282* @since 1.21283* @see java.nio.file.Files#newDirectoryStream(Path,String)1284*/1285public File[] listFiles(FilenameFilter filter) {1286String ss[] = normalizedList();1287if (ss == null) return null;1288ArrayList<File> files = new ArrayList<>();1289for (String s : ss)1290if ((filter == null) || filter.accept(this, s))1291files.add(new File(s, this));1292return files.toArray(new File[files.size()]);1293}12941295/**1296* Returns an array of abstract pathnames denoting the files and1297* directories in the directory denoted by this abstract pathname that1298* satisfy the specified filter. The behavior of this method is the same1299* as that of the {@link #listFiles()} method, except that the pathnames in1300* the returned array must satisfy the filter. If the given {@code filter}1301* is {@code null} then all pathnames are accepted. Otherwise, a pathname1302* satisfies the filter if and only if the value {@code true} results when1303* the {@link FileFilter#accept FileFilter.accept(File)} method of the1304* filter is invoked on the pathname.1305*1306* @param filter1307* A file filter1308*1309* @return An array of abstract pathnames denoting the files and1310* directories in the directory denoted by this abstract pathname.1311* The array will be empty if the directory is empty. Returns1312* {@code null} if this abstract pathname does not denote a1313* directory, or if an I/O error occurs.1314*1315* @throws SecurityException1316* If a security manager exists and its {@link1317* SecurityManager#checkRead(String)} method denies read access to1318* the directory1319*1320* @since 1.21321* @see java.nio.file.Files#newDirectoryStream(Path,java.nio.file.DirectoryStream.Filter)1322*/1323public File[] listFiles(FileFilter filter) {1324String ss[] = normalizedList();1325if (ss == null) return null;1326ArrayList<File> files = new ArrayList<>();1327for (String s : ss) {1328File f = new File(s, this);1329if ((filter == null) || filter.accept(f))1330files.add(f);1331}1332return files.toArray(new File[files.size()]);1333}13341335/**1336* Creates the directory named by this abstract pathname.1337*1338* @return <code>true</code> if and only if the directory was1339* created; <code>false</code> otherwise1340*1341* @throws SecurityException1342* If a security manager exists and its <code>{@link1343* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1344* method does not permit the named directory to be created1345*/1346public boolean mkdir() {1347SecurityManager security = System.getSecurityManager();1348if (security != null) {1349security.checkWrite(path);1350}1351if (isInvalid()) {1352return false;1353}1354return fs.createDirectory(this);1355}13561357/**1358* Creates the directory named by this abstract pathname, including any1359* necessary but nonexistent parent directories. Note that if this1360* operation fails it may have succeeded in creating some of the necessary1361* parent directories.1362*1363* @return <code>true</code> if and only if the directory was created,1364* along with all necessary parent directories; <code>false</code>1365* otherwise1366*1367* @throws SecurityException1368* If a security manager exists and its <code>{@link1369* java.lang.SecurityManager#checkRead(java.lang.String)}</code>1370* method does not permit verification of the existence of the1371* named directory and all necessary parent directories; or if1372* the <code>{@link1373* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1374* method does not permit the named directory and all necessary1375* parent directories to be created1376*/1377public boolean mkdirs() {1378if (exists()) {1379return false;1380}1381if (mkdir()) {1382return true;1383}1384File canonFile = null;1385try {1386canonFile = getCanonicalFile();1387} catch (IOException e) {1388return false;1389}13901391File parent = canonFile.getParentFile();1392return (parent != null && (parent.mkdirs() || parent.exists()) &&1393canonFile.mkdir());1394}13951396/**1397* Renames the file denoted by this abstract pathname.1398*1399* <p> Many aspects of the behavior of this method are inherently1400* platform-dependent: The rename operation might not be able to move a1401* file from one filesystem to another, it might not be atomic, and it1402* might not succeed if a file with the destination abstract pathname1403* already exists. The return value should always be checked to make sure1404* that the rename operation was successful.1405*1406* <p> Note that the {@link java.nio.file.Files} class defines the {@link1407* java.nio.file.Files#move move} method to move or rename a file in a1408* platform independent manner.1409*1410* @param dest The new abstract pathname for the named file1411*1412* @return <code>true</code> if and only if the renaming succeeded;1413* <code>false</code> otherwise1414*1415* @throws SecurityException1416* If a security manager exists and its <code>{@link1417* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1418* method denies write access to either the old or new pathnames1419*1420* @throws NullPointerException1421* If parameter <code>dest</code> is <code>null</code>1422*/1423public boolean renameTo(File dest) {1424SecurityManager security = System.getSecurityManager();1425if (security != null) {1426security.checkWrite(path);1427security.checkWrite(dest.path);1428}1429if (dest == null) {1430throw new NullPointerException();1431}1432if (this.isInvalid() || dest.isInvalid()) {1433return false;1434}1435return fs.rename(this, dest);1436}14371438/**1439* Sets the last-modified time of the file or directory named by this1440* abstract pathname.1441*1442* <p> All platforms support file-modification times to the nearest second,1443* but some provide more precision. The argument will be truncated to fit1444* the supported precision. If the operation succeeds and no intervening1445* operations on the file take place, then the next invocation of the1446* <code>{@link #lastModified}</code> method will return the (possibly1447* truncated) <code>time</code> argument that was passed to this method.1448*1449* @param time The new last-modified time, measured in milliseconds since1450* the epoch (00:00:00 GMT, January 1, 1970)1451*1452* @return <code>true</code> if and only if the operation succeeded;1453* <code>false</code> otherwise1454*1455* @throws IllegalArgumentException If the argument is negative1456*1457* @throws SecurityException1458* If a security manager exists and its <code>{@link1459* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1460* method denies write access to the named file1461*1462* @since 1.21463*/1464public boolean setLastModified(long time) {1465if (time < 0) throw new IllegalArgumentException("Negative time");1466SecurityManager security = System.getSecurityManager();1467if (security != null) {1468security.checkWrite(path);1469}1470if (isInvalid()) {1471return false;1472}1473return fs.setLastModifiedTime(this, time);1474}14751476/**1477* Marks the file or directory named by this abstract pathname so that1478* only read operations are allowed. After invoking this method the file1479* or directory will not change until it is either deleted or marked1480* to allow write access. On some platforms it may be possible to start the1481* Java virtual machine with special privileges that allow it to modify1482* files that are marked read-only. Whether or not a read-only file or1483* directory may be deleted depends upon the underlying system.1484*1485* @return <code>true</code> if and only if the operation succeeded;1486* <code>false</code> otherwise1487*1488* @throws SecurityException1489* If a security manager exists and its <code>{@link1490* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1491* method denies write access to the named file1492*1493* @since 1.21494*/1495public boolean setReadOnly() {1496SecurityManager security = System.getSecurityManager();1497if (security != null) {1498security.checkWrite(path);1499}1500if (isInvalid()) {1501return false;1502}1503return fs.setReadOnly(this);1504}15051506/**1507* Sets the owner's or everybody's write permission for this abstract1508* pathname. On some platforms it may be possible to start the Java virtual1509* machine with special privileges that allow it to modify files that1510* disallow write operations.1511*1512* <p> The {@link java.nio.file.Files} class defines methods that operate on1513* file attributes including file permissions. This may be used when finer1514* manipulation of file permissions is required.1515*1516* @param writable1517* If <code>true</code>, sets the access permission to allow write1518* operations; if <code>false</code> to disallow write operations1519*1520* @param ownerOnly1521* If <code>true</code>, the write permission applies only to the1522* owner's write permission; otherwise, it applies to everybody. If1523* the underlying file system can not distinguish the owner's write1524* permission from that of others, then the permission will apply to1525* everybody, regardless of this value.1526*1527* @return <code>true</code> if and only if the operation succeeded. The1528* operation will fail if the user does not have permission to change1529* the access permissions of this abstract pathname.1530*1531* @throws SecurityException1532* If a security manager exists and its <code>{@link1533* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1534* method denies write access to the named file1535*1536* @since 1.61537*/1538public boolean setWritable(boolean writable, boolean ownerOnly) {1539SecurityManager security = System.getSecurityManager();1540if (security != null) {1541security.checkWrite(path);1542}1543if (isInvalid()) {1544return false;1545}1546return fs.setPermission(this, FileSystem.ACCESS_WRITE, writable, ownerOnly);1547}15481549/**1550* A convenience method to set the owner's write permission for this abstract1551* pathname. On some platforms it may be possible to start the Java virtual1552* machine with special privileges that allow it to modify files that1553* disallow write operations.1554*1555* <p> An invocation of this method of the form <tt>file.setWritable(arg)</tt>1556* behaves in exactly the same way as the invocation1557*1558* <pre>1559* file.setWritable(arg, true) </pre>1560*1561* @param writable1562* If <code>true</code>, sets the access permission to allow write1563* operations; if <code>false</code> to disallow write operations1564*1565* @return <code>true</code> if and only if the operation succeeded. The1566* operation will fail if the user does not have permission to1567* change the access permissions of this abstract pathname.1568*1569* @throws SecurityException1570* If a security manager exists and its <code>{@link1571* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1572* method denies write access to the file1573*1574* @since 1.61575*/1576public boolean setWritable(boolean writable) {1577return setWritable(writable, true);1578}15791580/**1581* Sets the owner's or everybody's read permission for this abstract1582* pathname. On some platforms it may be possible to start the Java virtual1583* machine with special privileges that allow it to read files that are1584* marked as unreadable.1585*1586* <p> The {@link java.nio.file.Files} class defines methods that operate on1587* file attributes including file permissions. This may be used when finer1588* manipulation of file permissions is required.1589*1590* @param readable1591* If <code>true</code>, sets the access permission to allow read1592* operations; if <code>false</code> to disallow read operations1593*1594* @param ownerOnly1595* If <code>true</code>, the read permission applies only to the1596* owner's read permission; otherwise, it applies to everybody. If1597* the underlying file system can not distinguish the owner's read1598* permission from that of others, then the permission will apply to1599* everybody, regardless of this value.1600*1601* @return <code>true</code> if and only if the operation succeeded. The1602* operation will fail if the user does not have permission to1603* change the access permissions of this abstract pathname. If1604* <code>readable</code> is <code>false</code> and the underlying1605* file system does not implement a read permission, then the1606* operation will fail.1607*1608* @throws SecurityException1609* If a security manager exists and its <code>{@link1610* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1611* method denies write access to the file1612*1613* @since 1.61614*/1615public boolean setReadable(boolean readable, boolean ownerOnly) {1616SecurityManager security = System.getSecurityManager();1617if (security != null) {1618security.checkWrite(path);1619}1620if (isInvalid()) {1621return false;1622}1623return fs.setPermission(this, FileSystem.ACCESS_READ, readable, ownerOnly);1624}16251626/**1627* A convenience method to set the owner's read permission for this abstract1628* pathname. On some platforms it may be possible to start the Java virtual1629* machine with special privileges that allow it to read files that that are1630* marked as unreadable.1631*1632* <p>An invocation of this method of the form <tt>file.setReadable(arg)</tt>1633* behaves in exactly the same way as the invocation1634*1635* <pre>1636* file.setReadable(arg, true) </pre>1637*1638* @param readable1639* If <code>true</code>, sets the access permission to allow read1640* operations; if <code>false</code> to disallow read operations1641*1642* @return <code>true</code> if and only if the operation succeeded. The1643* operation will fail if the user does not have permission to1644* change the access permissions of this abstract pathname. If1645* <code>readable</code> is <code>false</code> and the underlying1646* file system does not implement a read permission, then the1647* operation will fail.1648*1649* @throws SecurityException1650* If a security manager exists and its <code>{@link1651* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1652* method denies write access to the file1653*1654* @since 1.61655*/1656public boolean setReadable(boolean readable) {1657return setReadable(readable, true);1658}16591660/**1661* Sets the owner's or everybody's execute permission for this abstract1662* pathname. On some platforms it may be possible to start the Java virtual1663* machine with special privileges that allow it to execute files that are1664* not marked executable.1665*1666* <p> The {@link java.nio.file.Files} class defines methods that operate on1667* file attributes including file permissions. This may be used when finer1668* manipulation of file permissions is required.1669*1670* @param executable1671* If <code>true</code>, sets the access permission to allow execute1672* operations; if <code>false</code> to disallow execute operations1673*1674* @param ownerOnly1675* If <code>true</code>, the execute permission applies only to the1676* owner's execute permission; otherwise, it applies to everybody.1677* If the underlying file system can not distinguish the owner's1678* execute permission from that of others, then the permission will1679* apply to everybody, regardless of this value.1680*1681* @return <code>true</code> if and only if the operation succeeded. The1682* operation will fail if the user does not have permission to1683* change the access permissions of this abstract pathname. If1684* <code>executable</code> is <code>false</code> and the underlying1685* file system does not implement an execute permission, then the1686* operation will fail.1687*1688* @throws SecurityException1689* If a security manager exists and its <code>{@link1690* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1691* method denies write access to the file1692*1693* @since 1.61694*/1695public boolean setExecutable(boolean executable, boolean ownerOnly) {1696SecurityManager security = System.getSecurityManager();1697if (security != null) {1698security.checkWrite(path);1699}1700if (isInvalid()) {1701return false;1702}1703return fs.setPermission(this, FileSystem.ACCESS_EXECUTE, executable, ownerOnly);1704}17051706/**1707* A convenience method to set the owner's execute permission for this1708* abstract pathname. On some platforms it may be possible to start the Java1709* virtual machine with special privileges that allow it to execute files1710* that are not marked executable.1711*1712* <p>An invocation of this method of the form <tt>file.setExcutable(arg)</tt>1713* behaves in exactly the same way as the invocation1714*1715* <pre>1716* file.setExecutable(arg, true) </pre>1717*1718* @param executable1719* If <code>true</code>, sets the access permission to allow execute1720* operations; if <code>false</code> to disallow execute operations1721*1722* @return <code>true</code> if and only if the operation succeeded. The1723* operation will fail if the user does not have permission to1724* change the access permissions of this abstract pathname. If1725* <code>executable</code> is <code>false</code> and the underlying1726* file system does not implement an execute permission, then the1727* operation will fail.1728*1729* @throws SecurityException1730* If a security manager exists and its <code>{@link1731* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>1732* method denies write access to the file1733*1734* @since 1.61735*/1736public boolean setExecutable(boolean executable) {1737return setExecutable(executable, true);1738}17391740/**1741* Tests whether the application can execute the file denoted by this1742* abstract pathname. On some platforms it may be possible to start the1743* Java virtual machine with special privileges that allow it to execute1744* files that are not marked executable. Consequently this method may return1745* {@code true} even though the file does not have execute permissions.1746*1747* @return <code>true</code> if and only if the abstract pathname exists1748* <em>and</em> the application is allowed to execute the file1749*1750* @throws SecurityException1751* If a security manager exists and its <code>{@link1752* java.lang.SecurityManager#checkExec(java.lang.String)}</code>1753* method denies execute access to the file1754*1755* @since 1.61756*/1757public boolean canExecute() {1758SecurityManager security = System.getSecurityManager();1759if (security != null) {1760security.checkExec(path);1761}1762if (isInvalid()) {1763return false;1764}1765return fs.checkAccess(this, FileSystem.ACCESS_EXECUTE);1766}176717681769/* -- Filesystem interface -- */17701771/**1772* List the available filesystem roots.1773*1774* <p> A particular Java platform may support zero or more1775* hierarchically-organized file systems. Each file system has a1776* {@code root} directory from which all other files in that file system1777* can be reached. Windows platforms, for example, have a root directory1778* for each active drive; UNIX platforms have a single root directory,1779* namely {@code "/"}. The set of available filesystem roots is affected1780* by various system-level operations such as the insertion or ejection of1781* removable media and the disconnecting or unmounting of physical or1782* virtual disk drives.1783*1784* <p> This method returns an array of {@code File} objects that denote the1785* root directories of the available filesystem roots. It is guaranteed1786* that the canonical pathname of any file physically present on the local1787* machine will begin with one of the roots returned by this method.1788*1789* <p> The canonical pathname of a file that resides on some other machine1790* and is accessed via a remote-filesystem protocol such as SMB or NFS may1791* or may not begin with one of the roots returned by this method. If the1792* pathname of a remote file is syntactically indistinguishable from the1793* pathname of a local file then it will begin with one of the roots1794* returned by this method. Thus, for example, {@code File} objects1795* denoting the root directories of the mapped network drives of a Windows1796* platform will be returned by this method, while {@code File} objects1797* containing UNC pathnames will not be returned by this method.1798*1799* <p> Unlike most methods in this class, this method does not throw1800* security exceptions. If a security manager exists and its {@link1801* SecurityManager#checkRead(String)} method denies read access to a1802* particular root directory, then that directory will not appear in the1803* result.1804*1805* @return An array of {@code File} objects denoting the available1806* filesystem roots, or {@code null} if the set of roots could not1807* be determined. The array will be empty if there are no1808* filesystem roots.1809*1810* @since 1.21811* @see java.nio.file.FileStore1812*/1813public static File[] listRoots() {1814return fs.listRoots();1815}181618171818/* -- Disk usage -- */18191820/**1821* Returns the size of the partition <a href="#partName">named</a> by this1822* abstract pathname.1823*1824* @return The size, in bytes, of the partition or <tt>0L</tt> if this1825* abstract pathname does not name a partition1826*1827* @throws SecurityException1828* If a security manager has been installed and it denies1829* {@link RuntimePermission}<tt>("getFileSystemAttributes")</tt>1830* or its {@link SecurityManager#checkRead(String)} method denies1831* read access to the file named by this abstract pathname1832*1833* @since 1.61834*/1835public long getTotalSpace() {1836SecurityManager sm = System.getSecurityManager();1837if (sm != null) {1838sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));1839sm.checkRead(path);1840}1841if (isInvalid()) {1842return 0L;1843}1844return fs.getSpace(this, FileSystem.SPACE_TOTAL);1845}18461847/**1848* Returns the number of unallocated bytes in the partition <a1849* href="#partName">named</a> by this abstract path name.1850*1851* <p> The returned number of unallocated bytes is a hint, but not1852* a guarantee, that it is possible to use most or any of these1853* bytes. The number of unallocated bytes is most likely to be1854* accurate immediately after this call. It is likely to be made1855* inaccurate by any external I/O operations including those made1856* on the system outside of this virtual machine. This method1857* makes no guarantee that write operations to this file system1858* will succeed.1859*1860* @return The number of unallocated bytes on the partition or <tt>0L</tt>1861* if the abstract pathname does not name a partition. This1862* value will be less than or equal to the total file system size1863* returned by {@link #getTotalSpace}.1864*1865* @throws SecurityException1866* If a security manager has been installed and it denies1867* {@link RuntimePermission}<tt>("getFileSystemAttributes")</tt>1868* or its {@link SecurityManager#checkRead(String)} method denies1869* read access to the file named by this abstract pathname1870*1871* @since 1.61872*/1873public long getFreeSpace() {1874SecurityManager sm = System.getSecurityManager();1875if (sm != null) {1876sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));1877sm.checkRead(path);1878}1879if (isInvalid()) {1880return 0L;1881}1882return fs.getSpace(this, FileSystem.SPACE_FREE);1883}18841885/**1886* Returns the number of bytes available to this virtual machine on the1887* partition <a href="#partName">named</a> by this abstract pathname. When1888* possible, this method checks for write permissions and other operating1889* system restrictions and will therefore usually provide a more accurate1890* estimate of how much new data can actually be written than {@link1891* #getFreeSpace}.1892*1893* <p> The returned number of available bytes is a hint, but not a1894* guarantee, that it is possible to use most or any of these bytes. The1895* number of unallocated bytes is most likely to be accurate immediately1896* after this call. It is likely to be made inaccurate by any external1897* I/O operations including those made on the system outside of this1898* virtual machine. This method makes no guarantee that write operations1899* to this file system will succeed.1900*1901* @return The number of available bytes on the partition or <tt>0L</tt>1902* if the abstract pathname does not name a partition. On1903* systems where this information is not available, this method1904* will be equivalent to a call to {@link #getFreeSpace}.1905*1906* @throws SecurityException1907* If a security manager has been installed and it denies1908* {@link RuntimePermission}<tt>("getFileSystemAttributes")</tt>1909* or its {@link SecurityManager#checkRead(String)} method denies1910* read access to the file named by this abstract pathname1911*1912* @since 1.61913*/1914public long getUsableSpace() {1915SecurityManager sm = System.getSecurityManager();1916if (sm != null) {1917sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));1918sm.checkRead(path);1919}1920if (isInvalid()) {1921return 0L;1922}1923return fs.getSpace(this, FileSystem.SPACE_USABLE);1924}19251926/* -- Temporary files -- */19271928private static class TempDirectory {1929private TempDirectory() { }19301931// temporary directory location1932private static final File tmpdir = new File(AccessController1933.doPrivileged(new GetPropertyAction("java.io.tmpdir")));1934static File location() {1935return tmpdir;1936}19371938// file name generation1939private static final SecureRandom random = new SecureRandom();1940static File generateFile(String prefix, String suffix, File dir)1941throws IOException1942{1943long n = random.nextLong();1944if (n == Long.MIN_VALUE) {1945n = 0; // corner case1946} else {1947n = Math.abs(n);1948}19491950// Use only the file name from the supplied prefix1951prefix = (new File(prefix)).getName();19521953String name = prefix + Long.toString(n) + suffix;1954File f = new File(dir, name);1955if (!name.equals(f.getName()) || f.isInvalid()) {1956if (System.getSecurityManager() != null)1957throw new IOException("Unable to create temporary file");1958else1959throw new IOException("Unable to create temporary file, " + f);1960}1961return f;1962}1963}19641965/**1966* <p> Creates a new empty file in the specified directory, using the1967* given prefix and suffix strings to generate its name. If this method1968* returns successfully then it is guaranteed that:1969*1970* <ol>1971* <li> The file denoted by the returned abstract pathname did not exist1972* before this method was invoked, and1973* <li> Neither this method nor any of its variants will return the same1974* abstract pathname again in the current invocation of the virtual1975* machine.1976* </ol>1977*1978* This method provides only part of a temporary-file facility. To arrange1979* for a file created by this method to be deleted automatically, use the1980* <code>{@link #deleteOnExit}</code> method.1981*1982* <p> The <code>prefix</code> argument must be at least three characters1983* long. It is recommended that the prefix be a short, meaningful string1984* such as <code>"hjb"</code> or <code>"mail"</code>. The1985* <code>suffix</code> argument may be <code>null</code>, in which case the1986* suffix <code>".tmp"</code> will be used.1987*1988* <p> To create the new file, the prefix and the suffix may first be1989* adjusted to fit the limitations of the underlying platform. If the1990* prefix is too long then it will be truncated, but its first three1991* characters will always be preserved. If the suffix is too long then it1992* too will be truncated, but if it begins with a period character1993* (<code>'.'</code>) then the period and the first three characters1994* following it will always be preserved. Once these adjustments have been1995* made the name of the new file will be generated by concatenating the1996* prefix, five or more internally-generated characters, and the suffix.1997*1998* <p> If the <code>directory</code> argument is <code>null</code> then the1999* system-dependent default temporary-file directory will be used. The2000* default temporary-file directory is specified by the system property2001* <code>java.io.tmpdir</code>. On UNIX systems the default value of this2002* property is typically <code>"/tmp"</code> or <code>"/var/tmp"</code>; on2003* Microsoft Windows systems it is typically <code>"C:\\WINNT\\TEMP"</code>. A different2004* value may be given to this system property when the Java virtual machine2005* is invoked, but programmatic changes to this property are not guaranteed2006* to have any effect upon the temporary directory used by this method.2007*2008* @param prefix The prefix string to be used in generating the file's2009* name; must be at least three characters long2010*2011* @param suffix The suffix string to be used in generating the file's2012* name; may be <code>null</code>, in which case the2013* suffix <code>".tmp"</code> will be used2014*2015* @param directory The directory in which the file is to be created, or2016* <code>null</code> if the default temporary-file2017* directory is to be used2018*2019* @return An abstract pathname denoting a newly-created empty file2020*2021* @throws IllegalArgumentException2022* If the <code>prefix</code> argument contains fewer than three2023* characters2024*2025* @throws IOException If a file could not be created2026*2027* @throws SecurityException2028* If a security manager exists and its <code>{@link2029* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>2030* method does not allow a file to be created2031*2032* @since 1.22033*/2034public static File createTempFile(String prefix, String suffix,2035File directory)2036throws IOException2037{2038if (prefix.length() < 3)2039throw new IllegalArgumentException("Prefix string too short");2040if (suffix == null)2041suffix = ".tmp";20422043File tmpdir = (directory != null) ? directory2044: TempDirectory.location();2045SecurityManager sm = System.getSecurityManager();2046File f;2047do {2048f = TempDirectory.generateFile(prefix, suffix, tmpdir);20492050if (sm != null) {2051try {2052sm.checkWrite(f.getPath());2053} catch (SecurityException se) {2054// don't reveal temporary directory location2055if (directory == null)2056throw new SecurityException("Unable to create temporary file");2057throw se;2058}2059}2060} while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0);20612062if (!fs.createFileExclusively(f.getPath()))2063throw new IOException("Unable to create temporary file");20642065return f;2066}20672068/**2069* Creates an empty file in the default temporary-file directory, using2070* the given prefix and suffix to generate its name. Invoking this method2071* is equivalent to invoking <code>{@link #createTempFile(java.lang.String,2072* java.lang.String, java.io.File)2073* createTempFile(prefix, suffix, null)}</code>.2074*2075* <p> The {@link2076* java.nio.file.Files#createTempFile(String,String,java.nio.file.attribute.FileAttribute[])2077* Files.createTempFile} method provides an alternative method to create an2078* empty file in the temporary-file directory. Files created by that method2079* may have more restrictive access permissions to files created by this2080* method and so may be more suited to security-sensitive applications.2081*2082* @param prefix The prefix string to be used in generating the file's2083* name; must be at least three characters long2084*2085* @param suffix The suffix string to be used in generating the file's2086* name; may be <code>null</code>, in which case the2087* suffix <code>".tmp"</code> will be used2088*2089* @return An abstract pathname denoting a newly-created empty file2090*2091* @throws IllegalArgumentException2092* If the <code>prefix</code> argument contains fewer than three2093* characters2094*2095* @throws IOException If a file could not be created2096*2097* @throws SecurityException2098* If a security manager exists and its <code>{@link2099* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>2100* method does not allow a file to be created2101*2102* @since 1.22103* @see java.nio.file.Files#createTempDirectory(String,FileAttribute[])2104*/2105public static File createTempFile(String prefix, String suffix)2106throws IOException2107{2108return createTempFile(prefix, suffix, null);2109}21102111/* -- Basic infrastructure -- */21122113/**2114* Compares two abstract pathnames lexicographically. The ordering2115* defined by this method depends upon the underlying system. On UNIX2116* systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows2117* systems it is not.2118*2119* @param pathname The abstract pathname to be compared to this abstract2120* pathname2121*2122* @return Zero if the argument is equal to this abstract pathname, a2123* value less than zero if this abstract pathname is2124* lexicographically less than the argument, or a value greater2125* than zero if this abstract pathname is lexicographically2126* greater than the argument2127*2128* @since 1.22129*/2130public int compareTo(File pathname) {2131return fs.compare(this, pathname);2132}21332134/**2135* Tests this abstract pathname for equality with the given object.2136* Returns <code>true</code> if and only if the argument is not2137* <code>null</code> and is an abstract pathname that denotes the same file2138* or directory as this abstract pathname. Whether or not two abstract2139* pathnames are equal depends upon the underlying system. On UNIX2140* systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows2141* systems it is not.2142*2143* @param obj The object to be compared with this abstract pathname2144*2145* @return <code>true</code> if and only if the objects are the same;2146* <code>false</code> otherwise2147*/2148public boolean equals(Object obj) {2149if ((obj != null) && (obj instanceof File)) {2150return compareTo((File)obj) == 0;2151}2152return false;2153}21542155/**2156* Computes a hash code for this abstract pathname. Because equality of2157* abstract pathnames is inherently system-dependent, so is the computation2158* of their hash codes. On UNIX systems, the hash code of an abstract2159* pathname is equal to the exclusive <em>or</em> of the hash code2160* of its pathname string and the decimal value2161* <code>1234321</code>. On Microsoft Windows systems, the hash2162* code is equal to the exclusive <em>or</em> of the hash code of2163* its pathname string converted to lower case and the decimal2164* value <code>1234321</code>. Locale is not taken into account on2165* lowercasing the pathname string.2166*2167* @return A hash code for this abstract pathname2168*/2169public int hashCode() {2170return fs.hashCode(this);2171}21722173/**2174* Returns the pathname string of this abstract pathname. This is just the2175* string returned by the <code>{@link #getPath}</code> method.2176*2177* @return The string form of this abstract pathname2178*/2179public String toString() {2180return getPath();2181}21822183/**2184* WriteObject is called to save this filename.2185* The separator character is saved also so it can be replaced2186* in case the path is reconstituted on a different host type.2187* <p>2188* @serialData Default fields followed by separator character.2189*/2190private synchronized void writeObject(java.io.ObjectOutputStream s)2191throws IOException2192{2193s.defaultWriteObject();2194s.writeChar(separatorChar); // Add the separator character2195}21962197/**2198* readObject is called to restore this filename.2199* The original separator character is read. If it is different2200* than the separator character on this system, then the old separator2201* is replaced by the local separator.2202*/2203private synchronized void readObject(java.io.ObjectInputStream s)2204throws IOException, ClassNotFoundException2205{2206ObjectInputStream.GetField fields = s.readFields();2207String pathField = (String)fields.get("path", null);2208char sep = s.readChar(); // read the previous separator char2209if (sep != separatorChar)2210pathField = pathField.replace(sep, separatorChar);2211String path = fs.normalize(pathField);2212UNSAFE.putObject(this, PATH_OFFSET, path);2213UNSAFE.putIntVolatile(this, PREFIX_LENGTH_OFFSET, fs.prefixLength(path));2214}22152216private static final long PATH_OFFSET;2217private static final long PREFIX_LENGTH_OFFSET;2218private static final sun.misc.Unsafe UNSAFE;2219static {2220try {2221sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();2222PATH_OFFSET = unsafe.objectFieldOffset(2223File.class.getDeclaredField("path"));2224PREFIX_LENGTH_OFFSET = unsafe.objectFieldOffset(2225File.class.getDeclaredField("prefixLength"));2226UNSAFE = unsafe;2227} catch (ReflectiveOperationException e) {2228throw new Error(e);2229}2230}223122322233/** use serialVersionUID from JDK 1.0.2 for interoperability */2234private static final long serialVersionUID = 301077366599181567L;22352236// -- Integration with java.nio.file --22372238private volatile transient Path filePath;22392240/**2241* Returns a {@link Path java.nio.file.Path} object constructed from the2242* this abstract path. The resulting {@code Path} is associated with the2243* {@link java.nio.file.FileSystems#getDefault default-filesystem}.2244*2245* <p> The first invocation of this method works as if invoking it were2246* equivalent to evaluating the expression:2247* <blockquote><pre>2248* {@link java.nio.file.FileSystems#getDefault FileSystems.getDefault}().{@link2249* java.nio.file.FileSystem#getPath getPath}(this.{@link #getPath getPath}());2250* </pre></blockquote>2251* Subsequent invocations of this method return the same {@code Path}.2252*2253* <p> If this abstract pathname is the empty abstract pathname then this2254* method returns a {@code Path} that may be used to access the current2255* user directory.2256*2257* @return a {@code Path} constructed from this abstract path2258*2259* @throws java.nio.file.InvalidPathException2260* if a {@code Path} object cannot be constructed from the abstract2261* path (see {@link java.nio.file.FileSystem#getPath FileSystem.getPath})2262*2263* @since 1.72264* @see Path#toFile2265*/2266public Path toPath() {2267Path result = filePath;2268if (result == null) {2269synchronized (this) {2270result = filePath;2271if (result == null) {2272result = FileSystems.getDefault().getPath(path);2273filePath = result;2274}2275}2276}2277return result;2278}2279}228022812282