2 * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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.
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).
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.
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
30 import java.net.MalformedURLException;
31 import java.net.URISyntaxException;
32 import java.util.List;
33 import java.util.ArrayList;
34 import java.security.AccessController;
35 import java.security.SecureRandom;
36 import java.nio.file.Path;
37 import java.nio.file.FileSystems;
38 import sun.security.action.GetPropertyAction;
41 * An abstract representation of file and directory pathnames.
43 * <p> User interfaces and operating systems use system-dependent <em>pathname
44 * strings</em> to name files and directories. This class presents an
45 * abstract, system-independent view of hierarchical pathnames. An
46 * <em>abstract pathname</em> has two components:
49 * <li> An optional system-dependent <em>prefix</em> string,
50 * such as a disk-drive specifier, <code>"/"</code> for the UNIX root
51 * directory, or <code>"\\\\"</code> for a Microsoft Windows UNC pathname, and
52 * <li> A sequence of zero or more string <em>names</em>.
55 * The first name in an abstract pathname may be a directory name or, in the
56 * case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name
57 * in an abstract pathname denotes a directory; the last name may denote
58 * either a directory or a file. The <em>empty</em> abstract pathname has no
59 * prefix and an empty name sequence.
61 * <p> The conversion of a pathname string to or from an abstract pathname is
62 * inherently system-dependent. When an abstract pathname is converted into a
63 * pathname string, each name is separated from the next by a single copy of
64 * the default <em>separator character</em>. The default name-separator
65 * character is defined by the system property <code>file.separator</code>, and
66 * is made available in the public static fields <code>{@link
67 * #separator}</code> and <code>{@link #separatorChar}</code> of this class.
68 * When a pathname string is converted into an abstract pathname, the names
69 * within it may be separated by the default name-separator character or by any
70 * other name-separator character that is supported by the underlying system.
72 * <p> A pathname, whether abstract or in string form, may be either
73 * <em>absolute</em> or <em>relative</em>. An absolute pathname is complete in
74 * that no other information is required in order to locate the file that it
75 * denotes. A relative pathname, in contrast, must be interpreted in terms of
76 * information taken from some other pathname. By default the classes in the
77 * <code>java.io</code> package always resolve relative pathnames against the
78 * current user directory. This directory is named by the system property
79 * <code>user.dir</code>, and is typically the directory in which the Java
80 * virtual machine was invoked.
82 * <p> The <em>parent</em> of an abstract pathname may be obtained by invoking
83 * the {@link #getParent} method of this class and consists of the pathname's
84 * prefix and each name in the pathname's name sequence except for the last.
85 * Each directory's absolute pathname is an ancestor of any <tt>File</tt>
86 * object with an absolute abstract pathname which begins with the directory's
87 * absolute pathname. For example, the directory denoted by the abstract
88 * pathname <tt>"/usr"</tt> is an ancestor of the directory denoted by the
89 * pathname <tt>"/usr/local/bin"</tt>.
91 * <p> The prefix concept is used to handle root directories on UNIX platforms,
92 * and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms,
97 * <li> For UNIX platforms, the prefix of an absolute pathname is always
98 * <code>"/"</code>. Relative pathnames have no prefix. The abstract pathname
99 * denoting the root directory has the prefix <code>"/"</code> and an empty
102 * <li> For Microsoft Windows platforms, the prefix of a pathname that contains a drive
103 * specifier consists of the drive letter followed by <code>":"</code> and
104 * possibly followed by <code>"\\"</code> if the pathname is absolute. The
105 * prefix of a UNC pathname is <code>"\\\\"</code>; the hostname and the share
106 * name are the first two names in the name sequence. A relative pathname that
107 * does not specify a drive has no prefix.
111 * <p> Instances of this class may or may not denote an actual file-system
112 * object such as a file or a directory. If it does denote such an object
113 * then that object resides in a <i>partition</i>. A partition is an
114 * operating system-specific portion of storage for a file system. A single
115 * storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may
116 * contain multiple partitions. The object, if any, will reside on the
117 * partition <a name="partName">named</a> by some ancestor of the absolute
118 * form of this pathname.
120 * <p> A file system may implement restrictions to certain operations on the
121 * actual file-system object, such as reading, writing, and executing. These
122 * restrictions are collectively known as <i>access permissions</i>. The file
123 * system may have multiple sets of access permissions on a single object.
124 * For example, one set may apply to the object's <i>owner</i>, and another
125 * may apply to all other users. The access permissions on an object may
126 * cause some methods in this class to fail.
128 * <p> Instances of the <code>File</code> class are immutable; that is, once
129 * created, the abstract pathname represented by a <code>File</code> object
132 * <h4>Interoperability with {@code java.nio.file} package</h4>
134 * <p> The <a href="../../java/nio/file/package-summary.html">{@code java.nio.file}</a>
135 * package defines interfaces and classes for the Java virtual machine to access
136 * files, file attributes, and file systems. This API may be used to overcome
137 * many of the limitations of the {@code java.io.File} class.
138 * The {@link #toPath toPath} method may be used to obtain a {@link
139 * Path} that uses the abstract path represented by a {@code File} object to
140 * locate a file. The resulting {@code Path} may be used with the {@link
141 * java.nio.file.Files} class to provide more efficient and extensive access to
142 * additional file operations, file attributes, and I/O exceptions to help
143 * diagnose errors when an operation on a file fails.
150 implements Serializable, Comparable<File>
154 * The FileSystem object representing the platform's local file system.
156 static private FileSystem fs = FileSystem.getFileSystem();
159 * This abstract pathname's normalized pathname string. A normalized
160 * pathname string uses the default name-separator character and does not
161 * contain any duplicate or redundant separators.
168 * The length of this abstract pathname's prefix, or zero if it has no
171 private transient int prefixLength;
174 * Returns the length of this abstract pathname's prefix.
175 * For use by FileSystem classes.
177 int getPrefixLength() {
182 * The system-dependent default name-separator character. This field is
183 * initialized to contain the first character of the value of the system
184 * property <code>file.separator</code>. On UNIX systems the value of this
185 * field is <code>'/'</code>; on Microsoft Windows systems it is <code>'\\'</code>.
187 * @see java.lang.System#getProperty(java.lang.String)
189 public static final char separatorChar = fs.getSeparator();
192 * The system-dependent default name-separator character, represented as a
193 * string for convenience. This string contains a single character, namely
194 * <code>{@link #separatorChar}</code>.
196 public static final String separator = "" + separatorChar;
199 * The system-dependent path-separator character. This field is
200 * initialized to contain the first character of the value of the system
201 * property <code>path.separator</code>. This character is used to
202 * separate filenames in a sequence of files given as a <em>path list</em>.
203 * On UNIX systems, this character is <code>':'</code>; on Microsoft Windows systems it
204 * is <code>';'</code>.
206 * @see java.lang.System#getProperty(java.lang.String)
208 public static final char pathSeparatorChar = fs.getPathSeparator();
211 * The system-dependent path-separator character, represented as a string
212 * for convenience. This string contains a single character, namely
213 * <code>{@link #pathSeparatorChar}</code>.
215 public static final String pathSeparator = "" + pathSeparatorChar;
218 /* -- Constructors -- */
221 * Internal constructor for already-normalized pathname strings.
223 private File(String pathname, int prefixLength) {
224 this.path = pathname;
225 this.prefixLength = prefixLength;
229 * Internal constructor for already-normalized pathname strings.
230 * The parameter order is used to disambiguate this method from the
231 * public(File, String) constructor.
233 private File(String child, File parent) {
234 assert parent.path != null;
235 assert (!parent.path.equals(""));
236 this.path = fs.resolve(parent.path, child);
237 this.prefixLength = parent.prefixLength;
241 * Creates a new <code>File</code> instance by converting the given
242 * pathname string into an abstract pathname. If the given string is
243 * the empty string, then the result is the empty abstract pathname.
245 * @param pathname A pathname string
246 * @throws NullPointerException
247 * If the <code>pathname</code> argument is <code>null</code>
249 public File(String pathname) {
250 if (pathname == null) {
251 throw new NullPointerException();
253 this.path = fs.normalize(pathname);
254 this.prefixLength = fs.prefixLength(this.path);
257 /* Note: The two-argument File constructors do not interpret an empty
258 parent abstract pathname as the current user directory. An empty parent
259 instead causes the child to be resolved against the system-dependent
260 directory defined by the FileSystem.getDefaultParent method. On Unix
261 this default is "/", while on Microsoft Windows it is "\\". This is required for
262 compatibility with the original behavior of this class. */
265 * Creates a new <code>File</code> instance from a parent pathname string
266 * and a child pathname string.
268 * <p> If <code>parent</code> is <code>null</code> then the new
269 * <code>File</code> instance is created as if by invoking the
270 * single-argument <code>File</code> constructor on the given
271 * <code>child</code> pathname string.
273 * <p> Otherwise the <code>parent</code> pathname string is taken to denote
274 * a directory, and the <code>child</code> pathname string is taken to
275 * denote either a directory or a file. If the <code>child</code> pathname
276 * string is absolute then it is converted into a relative pathname in a
277 * system-dependent way. If <code>parent</code> is the empty string then
278 * the new <code>File</code> instance is created by converting
279 * <code>child</code> into an abstract pathname and resolving the result
280 * against a system-dependent default directory. Otherwise each pathname
281 * string is converted into an abstract pathname and the child abstract
282 * pathname is resolved against the parent.
284 * @param parent The parent pathname string
285 * @param child The child pathname string
286 * @throws NullPointerException
287 * If <code>child</code> is <code>null</code>
289 public File(String parent, String child) {
291 throw new NullPointerException();
293 if (parent != null) {
294 if (parent.equals("")) {
295 this.path = fs.resolve(fs.getDefaultParent(),
296 fs.normalize(child));
298 this.path = fs.resolve(fs.normalize(parent),
299 fs.normalize(child));
302 this.path = fs.normalize(child);
304 this.prefixLength = fs.prefixLength(this.path);
308 * Creates a new <code>File</code> instance from a parent abstract
309 * pathname and a child pathname string.
311 * <p> If <code>parent</code> is <code>null</code> then the new
312 * <code>File</code> instance is created as if by invoking the
313 * single-argument <code>File</code> constructor on the given
314 * <code>child</code> pathname string.
316 * <p> Otherwise the <code>parent</code> abstract pathname is taken to
317 * denote a directory, and the <code>child</code> pathname string is taken
318 * to denote either a directory or a file. If the <code>child</code>
319 * pathname string is absolute then it is converted into a relative
320 * pathname in a system-dependent way. If <code>parent</code> is the empty
321 * abstract pathname then the new <code>File</code> instance is created by
322 * converting <code>child</code> into an abstract pathname and resolving
323 * the result against a system-dependent default directory. Otherwise each
324 * pathname string is converted into an abstract pathname and the child
325 * abstract pathname is resolved against the parent.
327 * @param parent The parent abstract pathname
328 * @param child The child pathname string
329 * @throws NullPointerException
330 * If <code>child</code> is <code>null</code>
332 public File(File parent, String child) {
334 throw new NullPointerException();
336 if (parent != null) {
337 if (parent.path.equals("")) {
338 this.path = fs.resolve(fs.getDefaultParent(),
339 fs.normalize(child));
341 this.path = fs.resolve(parent.path,
342 fs.normalize(child));
345 this.path = fs.normalize(child);
347 this.prefixLength = fs.prefixLength(this.path);
351 * Creates a new <tt>File</tt> instance by converting the given
352 * <tt>file:</tt> URI into an abstract pathname.
354 * <p> The exact form of a <tt>file:</tt> URI is system-dependent, hence
355 * the transformation performed by this constructor is also
358 * <p> For a given abstract pathname <i>f</i> it is guaranteed that
361 * new File(</tt><i> f</i><tt>.{@link #toURI() toURI}()).equals(</tt><i> f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}())
364 * so long as the original abstract pathname, the URI, and the new abstract
365 * pathname are all created in (possibly different invocations of) the same
366 * Java virtual machine. This relationship typically does not hold,
367 * however, when a <tt>file:</tt> URI that is created in a virtual machine
368 * on one operating system is converted into an abstract pathname in a
369 * virtual machine on a different operating system.
372 * An absolute, hierarchical URI with a scheme equal to
373 * <tt>"file"</tt>, a non-empty path component, and undefined
374 * authority, query, and fragment components
376 * @throws NullPointerException
377 * If <tt>uri</tt> is <tt>null</tt>
379 * @throws IllegalArgumentException
380 * If the preconditions on the parameter do not hold
386 public File(URI uri) {
388 // Check our many preconditions
389 if (!uri.isAbsolute())
390 throw new IllegalArgumentException("URI is not absolute");
392 throw new IllegalArgumentException("URI is not hierarchical");
393 String scheme = uri.getScheme();
394 if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
395 throw new IllegalArgumentException("URI scheme is not \"file\"");
396 if (uri.getAuthority() != null)
397 throw new IllegalArgumentException("URI has an authority component");
398 if (uri.getFragment() != null)
399 throw new IllegalArgumentException("URI has a fragment component");
400 if (uri.getQuery() != null)
401 throw new IllegalArgumentException("URI has a query component");
402 String p = uri.getPath();
404 throw new IllegalArgumentException("URI path component is empty");
406 // Okay, now initialize
407 p = fs.fromURIPath(p);
408 if (File.separatorChar != '/')
409 p = p.replace('/', File.separatorChar);
410 this.path = fs.normalize(p);
411 this.prefixLength = fs.prefixLength(this.path);
415 /* -- Path-component accessors -- */
418 * Returns the name of the file or directory denoted by this abstract
419 * pathname. This is just the last name in the pathname's name
420 * sequence. If the pathname's name sequence is empty, then the empty
421 * string is returned.
423 * @return The name of the file or directory denoted by this abstract
424 * pathname, or the empty string if this pathname's name sequence
427 public String getName() {
428 int index = path.lastIndexOf(separatorChar);
429 if (index < prefixLength) return path.substring(prefixLength);
430 return path.substring(index + 1);
434 * Returns the pathname string of this abstract pathname's parent, or
435 * <code>null</code> if this pathname does not name a parent directory.
437 * <p> The <em>parent</em> of an abstract pathname consists of the
438 * pathname's prefix, if any, and each name in the pathname's name
439 * sequence except for the last. If the name sequence is empty then
440 * the pathname does not name a parent directory.
442 * @return The pathname string of the parent directory named by this
443 * abstract pathname, or <code>null</code> if this pathname
444 * does not name a parent
446 public String getParent() {
447 int index = path.lastIndexOf(separatorChar);
448 if (index < prefixLength) {
449 if ((prefixLength > 0) && (path.length() > prefixLength))
450 return path.substring(0, prefixLength);
453 return path.substring(0, index);
457 * Returns the abstract pathname of this abstract pathname's parent,
458 * or <code>null</code> if this pathname does not name a parent
461 * <p> The <em>parent</em> of an abstract pathname consists of the
462 * pathname's prefix, if any, and each name in the pathname's name
463 * sequence except for the last. If the name sequence is empty then
464 * the pathname does not name a parent directory.
466 * @return The abstract pathname of the parent directory named by this
467 * abstract pathname, or <code>null</code> if this pathname
468 * does not name a parent
472 public File getParentFile() {
473 String p = this.getParent();
474 if (p == null) return null;
475 return new File(p, this.prefixLength);
479 * Converts this abstract pathname into a pathname string. The resulting
480 * string uses the {@link #separator default name-separator character} to
481 * separate the names in the name sequence.
483 * @return The string form of this abstract pathname
485 public String getPath() {
490 /* -- Path operations -- */
493 * Tests whether this abstract pathname is absolute. The definition of
494 * absolute pathname is system dependent. On UNIX systems, a pathname is
495 * absolute if its prefix is <code>"/"</code>. On Microsoft Windows systems, a
496 * pathname is absolute if its prefix is a drive specifier followed by
497 * <code>"\\"</code>, or if its prefix is <code>"\\\\"</code>.
499 * @return <code>true</code> if this abstract pathname is absolute,
500 * <code>false</code> otherwise
502 public boolean isAbsolute() {
503 return fs.isAbsolute(this);
507 * Returns the absolute pathname string of this abstract pathname.
509 * <p> If this abstract pathname is already absolute, then the pathname
510 * string is simply returned as if by the <code>{@link #getPath}</code>
511 * method. If this abstract pathname is the empty abstract pathname then
512 * the pathname string of the current user directory, which is named by the
513 * system property <code>user.dir</code>, is returned. Otherwise this
514 * pathname is resolved in a system-dependent way. On UNIX systems, a
515 * relative pathname is made absolute by resolving it against the current
516 * user directory. On Microsoft Windows systems, a relative pathname is made absolute
517 * by resolving it against the current directory of the drive named by the
518 * pathname, if any; if not, it is resolved against the current user
521 * @return The absolute pathname string denoting the same file or
522 * directory as this abstract pathname
524 * @throws SecurityException
525 * If a required system property value cannot be accessed.
527 * @see java.io.File#isAbsolute()
529 public String getAbsolutePath() {
530 return fs.resolve(this);
534 * Returns the absolute form of this abstract pathname. Equivalent to
535 * <code>new File(this.{@link #getAbsolutePath})</code>.
537 * @return The absolute abstract pathname denoting the same file or
538 * directory as this abstract pathname
540 * @throws SecurityException
541 * If a required system property value cannot be accessed.
545 public File getAbsoluteFile() {
546 String absPath = getAbsolutePath();
547 return new File(absPath, fs.prefixLength(absPath));
551 * Returns the canonical pathname string of this abstract pathname.
553 * <p> A canonical pathname is both absolute and unique. The precise
554 * definition of canonical form is system-dependent. This method first
555 * converts this pathname to absolute form if necessary, as if by invoking the
556 * {@link #getAbsolutePath} method, and then maps it to its unique form in a
557 * system-dependent way. This typically involves removing redundant names
558 * such as <tt>"."</tt> and <tt>".."</tt> from the pathname, resolving
559 * symbolic links (on UNIX platforms), and converting drive letters to a
560 * standard case (on Microsoft Windows platforms).
562 * <p> Every pathname that denotes an existing file or directory has a
563 * unique canonical form. Every pathname that denotes a nonexistent file
564 * or directory also has a unique canonical form. The canonical form of
565 * the pathname of a nonexistent file or directory may be different from
566 * the canonical form of the same pathname after the file or directory is
567 * created. Similarly, the canonical form of the pathname of an existing
568 * file or directory may be different from the canonical form of the same
569 * pathname after the file or directory is deleted.
571 * @return The canonical pathname string denoting the same file or
572 * directory as this abstract pathname
574 * @throws IOException
575 * If an I/O error occurs, which is possible because the
576 * construction of the canonical pathname may require
579 * @throws SecurityException
580 * If a required system property value cannot be accessed, or
581 * if a security manager exists and its <code>{@link
582 * java.lang.SecurityManager#checkRead}</code> method denies
583 * read access to the file
586 * @see Path#toRealPath
588 public String getCanonicalPath() throws IOException {
589 return fs.canonicalize(fs.resolve(this));
593 * Returns the canonical form of this abstract pathname. Equivalent to
594 * <code>new File(this.{@link #getCanonicalPath})</code>.
596 * @return The canonical pathname string denoting the same file or
597 * directory as this abstract pathname
599 * @throws IOException
600 * If an I/O error occurs, which is possible because the
601 * construction of the canonical pathname may require
604 * @throws SecurityException
605 * If a required system property value cannot be accessed, or
606 * if a security manager exists and its <code>{@link
607 * java.lang.SecurityManager#checkRead}</code> method denies
608 * read access to the file
611 * @see Path#toRealPath
613 public File getCanonicalFile() throws IOException {
614 String canonPath = getCanonicalPath();
615 return new File(canonPath, fs.prefixLength(canonPath));
618 private static String slashify(String path, boolean isDirectory) {
620 if (File.separatorChar != '/')
621 p = p.replace(File.separatorChar, '/');
622 if (!p.startsWith("/"))
624 if (!p.endsWith("/") && isDirectory)
630 * Converts this abstract pathname into a <code>file:</code> URL. The
631 * exact form of the URL is system-dependent. If it can be determined that
632 * the file denoted by this abstract pathname is a directory, then the
633 * resulting URL will end with a slash.
635 * @return A URL object representing the equivalent file URL
637 * @throws MalformedURLException
638 * If the path cannot be parsed as a URL
642 * @see java.net.URI#toURL()
646 * @deprecated This method does not automatically escape characters that
647 * are illegal in URLs. It is recommended that new code convert an
648 * abstract pathname into a URL by first converting it into a URI, via the
649 * {@link #toURI() toURI} method, and then converting the URI into a URL
650 * via the {@link java.net.URI#toURL() URI.toURL} method.
653 public URL toURL() throws MalformedURLException {
654 return new URL("file", "", slashify(getAbsolutePath(), isDirectory()));
658 * Constructs a <tt>file:</tt> URI that represents this abstract pathname.
660 * <p> The exact form of the URI is system-dependent. If it can be
661 * determined that the file denoted by this abstract pathname is a
662 * directory, then the resulting URI will end with a slash.
664 * <p> For a given abstract pathname <i>f</i>, it is guaranteed that
667 * new {@link #File(java.net.URI) File}(</tt><i> f</i><tt>.toURI()).equals(</tt><i> f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}())
670 * so long as the original abstract pathname, the URI, and the new abstract
671 * pathname are all created in (possibly different invocations of) the same
672 * Java virtual machine. Due to the system-dependent nature of abstract
673 * pathnames, however, this relationship typically does not hold when a
674 * <tt>file:</tt> URI that is created in a virtual machine on one operating
675 * system is converted into an abstract pathname in a virtual machine on a
676 * different operating system.
678 * <p> Note that when this abstract pathname represents a UNC pathname then
679 * all components of the UNC (including the server name component) are encoded
680 * in the {@code URI} path. The authority component is undefined, meaning
681 * that it is represented as {@code null}. The {@link Path} class defines the
682 * {@link Path#toUri toUri} method to encode the server name in the authority
683 * component of the resulting {@code URI}. The {@link #toPath toPath} method
684 * may be used to obtain a {@code Path} representing this abstract pathname.
686 * @return An absolute, hierarchical URI with a scheme equal to
687 * <tt>"file"</tt>, a path representing this abstract pathname,
688 * and undefined authority, query, and fragment components
689 * @throws SecurityException If a required system property value cannot
692 * @see #File(java.net.URI)
694 * @see java.net.URI#toURL()
699 File f = getAbsoluteFile();
700 String sp = slashify(f.getPath(), f.isDirectory());
701 if (sp.startsWith("//"))
703 return new URI("file", null, sp, null);
704 } catch (URISyntaxException x) {
705 throw new Error(x); // Can't happen
710 /* -- Attribute accessors -- */
713 * Tests whether the application can read the file denoted by this
716 * @return <code>true</code> if and only if the file specified by this
717 * abstract pathname exists <em>and</em> can be read by the
718 * application; <code>false</code> otherwise
720 * @throws SecurityException
721 * If a security manager exists and its <code>{@link
722 * java.lang.SecurityManager#checkRead(java.lang.String)}</code>
723 * method denies read access to the file
725 public boolean canRead() {
726 SecurityManager security = System.getSecurityManager();
727 if (security != null) {
728 security.checkRead(path);
730 return fs.checkAccess(this, FileSystem.ACCESS_READ);
734 * Tests whether the application can modify the file denoted by this
737 * @return <code>true</code> if and only if the file system actually
738 * contains a file denoted by this abstract pathname <em>and</em>
739 * the application is allowed to write to the file;
740 * <code>false</code> otherwise.
742 * @throws SecurityException
743 * If a security manager exists and its <code>{@link
744 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
745 * method denies write access to the file
747 public boolean canWrite() {
748 SecurityManager security = System.getSecurityManager();
749 if (security != null) {
750 security.checkWrite(path);
752 return fs.checkAccess(this, FileSystem.ACCESS_WRITE);
756 * Tests whether the file or directory denoted by this abstract pathname
759 * @return <code>true</code> if and only if the file or directory denoted
760 * by this abstract pathname exists; <code>false</code> otherwise
762 * @throws SecurityException
763 * If a security manager exists and its <code>{@link
764 * java.lang.SecurityManager#checkRead(java.lang.String)}</code>
765 * method denies read access to the file or directory
767 public boolean exists() {
768 SecurityManager security = System.getSecurityManager();
769 if (security != null) {
770 security.checkRead(path);
772 return ((fs.getBooleanAttributes(this) & FileSystem.BA_EXISTS) != 0);
776 * Tests whether the file denoted by this abstract pathname is a
779 * <p> Where it is required to distinguish an I/O exception from the case
780 * that the file is not a directory, or where several attributes of the
781 * same file are required at the same time, then the {@link
782 * java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
783 * Files.readAttributes} method may be used.
785 * @return <code>true</code> if and only if the file denoted by this
786 * abstract pathname exists <em>and</em> is a directory;
787 * <code>false</code> otherwise
789 * @throws SecurityException
790 * If a security manager exists and its <code>{@link
791 * java.lang.SecurityManager#checkRead(java.lang.String)}</code>
792 * method denies read access to the file
794 public boolean isDirectory() {
795 SecurityManager security = System.getSecurityManager();
796 if (security != null) {
797 security.checkRead(path);
799 return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY)
804 * Tests whether the file denoted by this abstract pathname is a normal
805 * file. A file is <em>normal</em> if it is not a directory and, in
806 * addition, satisfies other system-dependent criteria. Any non-directory
807 * file created by a Java application is guaranteed to be a normal file.
809 * <p> Where it is required to distinguish an I/O exception from the case
810 * that the file is not a normal file, or where several attributes of the
811 * same file are required at the same time, then the {@link
812 * java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
813 * Files.readAttributes} method may be used.
815 * @return <code>true</code> if and only if the file denoted by this
816 * abstract pathname exists <em>and</em> is a normal file;
817 * <code>false</code> otherwise
819 * @throws SecurityException
820 * If a security manager exists and its <code>{@link
821 * java.lang.SecurityManager#checkRead(java.lang.String)}</code>
822 * method denies read access to the file
824 public boolean isFile() {
825 SecurityManager security = System.getSecurityManager();
826 if (security != null) {
827 security.checkRead(path);
829 return ((fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0);
833 * Tests whether the file named by this abstract pathname is a hidden
834 * file. The exact definition of <em>hidden</em> is system-dependent. On
835 * UNIX systems, a file is considered to be hidden if its name begins with
836 * a period character (<code>'.'</code>). On Microsoft Windows systems, a file is
837 * considered to be hidden if it has been marked as such in the filesystem.
839 * @return <code>true</code> if and only if the file denoted by this
840 * abstract pathname is hidden according to the conventions of the
841 * underlying platform
843 * @throws SecurityException
844 * If a security manager exists and its <code>{@link
845 * java.lang.SecurityManager#checkRead(java.lang.String)}</code>
846 * method denies read access to the file
850 public boolean isHidden() {
851 SecurityManager security = System.getSecurityManager();
852 if (security != null) {
853 security.checkRead(path);
855 return ((fs.getBooleanAttributes(this) & FileSystem.BA_HIDDEN) != 0);
859 * Returns the time that the file denoted by this abstract pathname was
862 * <p> Where it is required to distinguish an I/O exception from the case
863 * where {@code 0L} is returned, or where several attributes of the
864 * same file are required at the same time, or where the time of last
865 * access or the creation time are required, then the {@link
866 * java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
867 * Files.readAttributes} method may be used.
869 * @return A <code>long</code> value representing the time the file was
870 * last modified, measured in milliseconds since the epoch
871 * (00:00:00 GMT, January 1, 1970), or <code>0L</code> if the
872 * file does not exist or if an I/O error occurs
874 * @throws SecurityException
875 * If a security manager exists and its <code>{@link
876 * java.lang.SecurityManager#checkRead(java.lang.String)}</code>
877 * method denies read access to the file
879 public long lastModified() {
880 SecurityManager security = System.getSecurityManager();
881 if (security != null) {
882 security.checkRead(path);
884 return fs.getLastModifiedTime(this);
888 * Returns the length of the file denoted by this abstract pathname.
889 * The return value is unspecified if this pathname denotes a directory.
891 * <p> Where it is required to distinguish an I/O exception from the case
892 * that {@code 0L} is returned, or where several attributes of the same file
893 * are required at the same time, then the {@link
894 * java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
895 * Files.readAttributes} method may be used.
897 * @return The length, in bytes, of the file denoted by this abstract
898 * pathname, or <code>0L</code> if the file does not exist. Some
899 * operating systems may return <code>0L</code> for pathnames
900 * denoting system-dependent entities such as devices or pipes.
902 * @throws SecurityException
903 * If a security manager exists and its <code>{@link
904 * java.lang.SecurityManager#checkRead(java.lang.String)}</code>
905 * method denies read access to the file
907 public long length() {
908 SecurityManager security = System.getSecurityManager();
909 if (security != null) {
910 security.checkRead(path);
912 return fs.getLength(this);
916 /* -- File operations -- */
919 * Atomically creates a new, empty file named by this abstract pathname if
920 * and only if a file with this name does not yet exist. The check for the
921 * existence of the file and the creation of the file if it does not exist
922 * are a single operation that is atomic with respect to all other
923 * filesystem activities that might affect the file.
925 * Note: this method should <i>not</i> be used for file-locking, as
926 * the resulting protocol cannot be made to work reliably. The
927 * {@link java.nio.channels.FileLock FileLock}
928 * facility should be used instead.
930 * @return <code>true</code> if the named file does not exist and was
931 * successfully created; <code>false</code> if the named file
934 * @throws IOException
935 * If an I/O error occurred
937 * @throws SecurityException
938 * If a security manager exists and its <code>{@link
939 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
940 * method denies write access to the file
944 public boolean createNewFile() throws IOException {
945 SecurityManager security = System.getSecurityManager();
946 if (security != null) security.checkWrite(path);
947 return fs.createFileExclusively(path);
951 * Deletes the file or directory denoted by this abstract pathname. If
952 * this pathname denotes a directory, then the directory must be empty in
953 * order to be deleted.
955 * <p> Note that the {@link java.nio.file.Files} class defines the {@link
956 * java.nio.file.Files#delete(Path) delete} method to throw an {@link IOException}
957 * when a file cannot be deleted. This is useful for error reporting and to
958 * diagnose why a file cannot be deleted.
960 * @return <code>true</code> if and only if the file or directory is
961 * successfully deleted; <code>false</code> otherwise
963 * @throws SecurityException
964 * If a security manager exists and its <code>{@link
965 * java.lang.SecurityManager#checkDelete}</code> method denies
966 * delete access to the file
968 public boolean delete() {
969 SecurityManager security = System.getSecurityManager();
970 if (security != null) {
971 security.checkDelete(path);
973 return fs.delete(this);
977 * Requests that the file or directory denoted by this abstract
978 * pathname be deleted when the virtual machine terminates.
979 * Files (or directories) are deleted in the reverse order that
980 * they are registered. Invoking this method to delete a file or
981 * directory that is already registered for deletion has no effect.
982 * Deletion will be attempted only for normal termination of the
983 * virtual machine, as defined by the Java Language Specification.
985 * <p> Once deletion has been requested, it is not possible to cancel the
986 * request. This method should therefore be used with care.
989 * Note: this method should <i>not</i> be used for file-locking, as
990 * the resulting protocol cannot be made to work reliably. The
991 * {@link java.nio.channels.FileLock FileLock}
992 * facility should be used instead.
994 * @throws SecurityException
995 * If a security manager exists and its <code>{@link
996 * java.lang.SecurityManager#checkDelete}</code> method denies
997 * delete access to the file
1003 public void deleteOnExit() {
1004 SecurityManager security = System.getSecurityManager();
1005 if (security != null) {
1006 security.checkDelete(path);
1008 DeleteOnExitHook.add(path);
1012 * Returns an array of strings naming the files and directories in the
1013 * directory denoted by this abstract pathname.
1015 * <p> If this abstract pathname does not denote a directory, then this
1016 * method returns {@code null}. Otherwise an array of strings is
1017 * returned, one for each file or directory in the directory. Names
1018 * denoting the directory itself and the directory's parent directory are
1019 * not included in the result. Each string is a file name rather than a
1022 * <p> There is no guarantee that the name strings in the resulting array
1023 * will appear in any specific order; they are not, in particular,
1024 * guaranteed to appear in alphabetical order.
1026 * <p> Note that the {@link java.nio.file.Files} class defines the {@link
1027 * java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method to
1028 * open a directory and iterate over the names of the files in the directory.
1029 * This may use less resources when working with very large directories, and
1030 * may be more responsive when working with remote directories.
1032 * @return An array of strings naming the files and directories in the
1033 * directory denoted by this abstract pathname. The array will be
1034 * empty if the directory is empty. Returns {@code null} if
1035 * this abstract pathname does not denote a directory, or if an
1038 * @throws SecurityException
1039 * If a security manager exists and its {@link
1040 * SecurityManager#checkRead(String)} method denies read access to
1043 public String[] list() {
1044 SecurityManager security = System.getSecurityManager();
1045 if (security != null) {
1046 security.checkRead(path);
1048 return fs.list(this);
1052 * Returns an array of strings naming the files and directories in the
1053 * directory denoted by this abstract pathname that satisfy the specified
1054 * filter. The behavior of this method is the same as that of the
1055 * {@link #list()} method, except that the strings in the returned array
1056 * must satisfy the filter. If the given {@code filter} is {@code null}
1057 * then all names are accepted. Otherwise, a name satisfies the filter if
1058 * and only if the value {@code true} results when the {@link
1059 * FilenameFilter#accept FilenameFilter.accept(File, String)} method
1060 * of the filter is invoked on this abstract pathname and the name of a
1061 * file or directory in the directory that it denotes.
1066 * @return An array of strings naming the files and directories in the
1067 * directory denoted by this abstract pathname that were accepted
1068 * by the given {@code filter}. The array will be empty if the
1069 * directory is empty or if no names were accepted by the filter.
1070 * Returns {@code null} if this abstract pathname does not denote
1071 * a directory, or if an I/O error occurs.
1073 * @throws SecurityException
1074 * If a security manager exists and its {@link
1075 * SecurityManager#checkRead(String)} method denies read access to
1078 * @see java.nio.file.Files#newDirectoryStream(Path,String)
1080 public String[] list(FilenameFilter filter) {
1081 String names[] = list();
1082 if ((names == null) || (filter == null)) {
1085 List<String> v = new ArrayList<>();
1086 for (int i = 0 ; i < names.length ; i++) {
1087 if (filter.accept(this, names[i])) {
1091 return v.toArray(new String[v.size()]);
1095 * Returns an array of abstract pathnames denoting the files in the
1096 * directory denoted by this abstract pathname.
1098 * <p> If this abstract pathname does not denote a directory, then this
1099 * method returns {@code null}. Otherwise an array of {@code File} objects
1100 * is returned, one for each file or directory in the directory. Pathnames
1101 * denoting the directory itself and the directory's parent directory are
1102 * not included in the result. Each resulting abstract pathname is
1103 * constructed from this abstract pathname using the {@link #File(File,
1104 * String) File(File, String)} constructor. Therefore if this
1105 * pathname is absolute then each resulting pathname is absolute; if this
1106 * pathname is relative then each resulting pathname will be relative to
1107 * the same directory.
1109 * <p> There is no guarantee that the name strings in the resulting array
1110 * will appear in any specific order; they are not, in particular,
1111 * guaranteed to appear in alphabetical order.
1113 * <p> Note that the {@link java.nio.file.Files} class defines the {@link
1114 * java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method
1115 * to open a directory and iterate over the names of the files in the
1116 * directory. This may use less resources when working with very large
1119 * @return An array of abstract pathnames denoting the files and
1120 * directories in the directory denoted by this abstract pathname.
1121 * The array will be empty if the directory is empty. Returns
1122 * {@code null} if this abstract pathname does not denote a
1123 * directory, or if an I/O error occurs.
1125 * @throws SecurityException
1126 * If a security manager exists and its {@link
1127 * SecurityManager#checkRead(String)} method denies read access to
1132 public File[] listFiles() {
1133 String[] ss = list();
1134 if (ss == null) return null;
1136 File[] fs = new File[n];
1137 for (int i = 0; i < n; i++) {
1138 fs[i] = new File(ss[i], this);
1144 * Returns an array of abstract pathnames denoting the files and
1145 * directories in the directory denoted by this abstract pathname that
1146 * satisfy the specified filter. The behavior of this method is the same
1147 * as that of the {@link #listFiles()} method, except that the pathnames in
1148 * the returned array must satisfy the filter. If the given {@code filter}
1149 * is {@code null} then all pathnames are accepted. Otherwise, a pathname
1150 * satisfies the filter if and only if the value {@code true} results when
1151 * the {@link FilenameFilter#accept
1152 * FilenameFilter.accept(File, String)} method of the filter is
1153 * invoked on this abstract pathname and the name of a file or directory in
1154 * the directory that it denotes.
1159 * @return An array of abstract pathnames denoting the files and
1160 * directories in the directory denoted by this abstract pathname.
1161 * The array will be empty if the directory is empty. Returns
1162 * {@code null} if this abstract pathname does not denote a
1163 * directory, or if an I/O error occurs.
1165 * @throws SecurityException
1166 * If a security manager exists and its {@link
1167 * SecurityManager#checkRead(String)} method denies read access to
1171 * @see java.nio.file.Files#newDirectoryStream(Path,String)
1173 public File[] listFiles(FilenameFilter filter) {
1174 String ss[] = list();
1175 if (ss == null) return null;
1176 ArrayList<File> files = new ArrayList<>();
1178 if ((filter == null) || filter.accept(this, s))
1179 files.add(new File(s, this));
1180 return files.toArray(new File[files.size()]);
1184 * Returns an array of abstract pathnames denoting the files and
1185 * directories in the directory denoted by this abstract pathname that
1186 * satisfy the specified filter. The behavior of this method is the same
1187 * as that of the {@link #listFiles()} method, except that the pathnames in
1188 * the returned array must satisfy the filter. If the given {@code filter}
1189 * is {@code null} then all pathnames are accepted. Otherwise, a pathname
1190 * satisfies the filter if and only if the value {@code true} results when
1191 * the {@link FileFilter#accept FileFilter.accept(File)} method of the
1192 * filter is invoked on the pathname.
1197 * @return An array of abstract pathnames denoting the files and
1198 * directories in the directory denoted by this abstract pathname.
1199 * The array will be empty if the directory is empty. Returns
1200 * {@code null} if this abstract pathname does not denote a
1201 * directory, or if an I/O error occurs.
1203 * @throws SecurityException
1204 * If a security manager exists and its {@link
1205 * SecurityManager#checkRead(String)} method denies read access to
1209 * @see java.nio.file.Files#newDirectoryStream(Path,java.nio.file.DirectoryStream.Filter)
1211 public File[] listFiles(FileFilter filter) {
1212 String ss[] = list();
1213 if (ss == null) return null;
1214 ArrayList<File> files = new ArrayList<>();
1215 for (String s : ss) {
1216 File f = new File(s, this);
1217 if ((filter == null) || filter.accept(f))
1220 return files.toArray(new File[files.size()]);
1224 * Creates the directory named by this abstract pathname.
1226 * @return <code>true</code> if and only if the directory was
1227 * created; <code>false</code> otherwise
1229 * @throws SecurityException
1230 * If a security manager exists and its <code>{@link
1231 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1232 * method does not permit the named directory to be created
1234 public boolean mkdir() {
1235 SecurityManager security = System.getSecurityManager();
1236 if (security != null) {
1237 security.checkWrite(path);
1239 return fs.createDirectory(this);
1243 * Creates the directory named by this abstract pathname, including any
1244 * necessary but nonexistent parent directories. Note that if this
1245 * operation fails it may have succeeded in creating some of the necessary
1246 * parent directories.
1248 * @return <code>true</code> if and only if the directory was created,
1249 * along with all necessary parent directories; <code>false</code>
1252 * @throws SecurityException
1253 * If a security manager exists and its <code>{@link
1254 * java.lang.SecurityManager#checkRead(java.lang.String)}</code>
1255 * method does not permit verification of the existence of the
1256 * named directory and all necessary parent directories; or if
1258 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1259 * method does not permit the named directory and all necessary
1260 * parent directories to be created
1262 public boolean mkdirs() {
1269 File canonFile = null;
1271 canonFile = getCanonicalFile();
1272 } catch (IOException e) {
1276 File parent = canonFile.getParentFile();
1277 return (parent != null && (parent.mkdirs() || parent.exists()) &&
1282 * Renames the file denoted by this abstract pathname.
1284 * <p> Many aspects of the behavior of this method are inherently
1285 * platform-dependent: The rename operation might not be able to move a
1286 * file from one filesystem to another, it might not be atomic, and it
1287 * might not succeed if a file with the destination abstract pathname
1288 * already exists. The return value should always be checked to make sure
1289 * that the rename operation was successful.
1291 * <p> Note that the {@link java.nio.file.Files} class defines the {@link
1292 * java.nio.file.Files#move move} method to move or rename a file in a
1293 * platform independent manner.
1295 * @param dest The new abstract pathname for the named file
1297 * @return <code>true</code> if and only if the renaming succeeded;
1298 * <code>false</code> otherwise
1300 * @throws SecurityException
1301 * If a security manager exists and its <code>{@link
1302 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1303 * method denies write access to either the old or new pathnames
1305 * @throws NullPointerException
1306 * If parameter <code>dest</code> is <code>null</code>
1308 public boolean renameTo(File dest) {
1309 SecurityManager security = System.getSecurityManager();
1310 if (security != null) {
1311 security.checkWrite(path);
1312 security.checkWrite(dest.path);
1314 return fs.rename(this, dest);
1318 * Sets the last-modified time of the file or directory named by this
1319 * abstract pathname.
1321 * <p> All platforms support file-modification times to the nearest second,
1322 * but some provide more precision. The argument will be truncated to fit
1323 * the supported precision. If the operation succeeds and no intervening
1324 * operations on the file take place, then the next invocation of the
1325 * <code>{@link #lastModified}</code> method will return the (possibly
1326 * truncated) <code>time</code> argument that was passed to this method.
1328 * @param time The new last-modified time, measured in milliseconds since
1329 * the epoch (00:00:00 GMT, January 1, 1970)
1331 * @return <code>true</code> if and only if the operation succeeded;
1332 * <code>false</code> otherwise
1334 * @throws IllegalArgumentException If the argument is negative
1336 * @throws SecurityException
1337 * If a security manager exists and its <code>{@link
1338 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1339 * method denies write access to the named file
1343 public boolean setLastModified(long time) {
1344 if (time < 0) throw new IllegalArgumentException("Negative time");
1345 SecurityManager security = System.getSecurityManager();
1346 if (security != null) {
1347 security.checkWrite(path);
1349 return fs.setLastModifiedTime(this, time);
1353 * Marks the file or directory named by this abstract pathname so that
1354 * only read operations are allowed. After invoking this method the file
1355 * or directory is guaranteed not to change until it is either deleted or
1356 * marked to allow write access. Whether or not a read-only file or
1357 * directory may be deleted depends upon the underlying system.
1359 * @return <code>true</code> if and only if the operation succeeded;
1360 * <code>false</code> otherwise
1362 * @throws SecurityException
1363 * If a security manager exists and its <code>{@link
1364 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1365 * method denies write access to the named file
1369 public boolean setReadOnly() {
1370 SecurityManager security = System.getSecurityManager();
1371 if (security != null) {
1372 security.checkWrite(path);
1374 return fs.setReadOnly(this);
1378 * Sets the owner's or everybody's write permission for this abstract
1381 * <p> The {@link java.nio.file.Files} class defines methods that operate on
1382 * file attributes including file permissions. This may be used when finer
1383 * manipulation of file permissions is required.
1386 * If <code>true</code>, sets the access permission to allow write
1387 * operations; if <code>false</code> to disallow write operations
1390 * If <code>true</code>, the write permission applies only to the
1391 * owner's write permission; otherwise, it applies to everybody. If
1392 * the underlying file system can not distinguish the owner's write
1393 * permission from that of others, then the permission will apply to
1394 * everybody, regardless of this value.
1396 * @return <code>true</code> if and only if the operation succeeded. The
1397 * operation will fail if the user does not have permission to change
1398 * the access permissions of this abstract pathname.
1400 * @throws SecurityException
1401 * If a security manager exists and its <code>{@link
1402 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1403 * method denies write access to the named file
1407 public boolean setWritable(boolean writable, boolean ownerOnly) {
1408 SecurityManager security = System.getSecurityManager();
1409 if (security != null) {
1410 security.checkWrite(path);
1412 return fs.setPermission(this, FileSystem.ACCESS_WRITE, writable, ownerOnly);
1416 * A convenience method to set the owner's write permission for this abstract
1419 * <p> An invocation of this method of the form <tt>file.setWritable(arg)</tt>
1420 * behaves in exactly the same way as the invocation
1423 * file.setWritable(arg, true) </pre>
1426 * If <code>true</code>, sets the access permission to allow write
1427 * operations; if <code>false</code> to disallow write operations
1429 * @return <code>true</code> if and only if the operation succeeded. The
1430 * operation will fail if the user does not have permission to
1431 * change the access permissions of this abstract pathname.
1433 * @throws SecurityException
1434 * If a security manager exists and its <code>{@link
1435 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1436 * method denies write access to the file
1440 public boolean setWritable(boolean writable) {
1441 return setWritable(writable, true);
1445 * Sets the owner's or everybody's read permission for this abstract
1448 * <p> The {@link java.nio.file.Files} class defines methods that operate on
1449 * file attributes including file permissions. This may be used when finer
1450 * manipulation of file permissions is required.
1453 * If <code>true</code>, sets the access permission to allow read
1454 * operations; if <code>false</code> to disallow read operations
1457 * If <code>true</code>, the read permission applies only to the
1458 * owner's read permission; otherwise, it applies to everybody. If
1459 * the underlying file system can not distinguish the owner's read
1460 * permission from that of others, then the permission will apply to
1461 * everybody, regardless of this value.
1463 * @return <code>true</code> if and only if the operation succeeded. The
1464 * operation will fail if the user does not have permission to
1465 * change the access permissions of this abstract pathname. If
1466 * <code>readable</code> is <code>false</code> and the underlying
1467 * file system does not implement a read permission, then the
1468 * operation will fail.
1470 * @throws SecurityException
1471 * If a security manager exists and its <code>{@link
1472 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1473 * method denies write access to the file
1477 public boolean setReadable(boolean readable, boolean ownerOnly) {
1478 SecurityManager security = System.getSecurityManager();
1479 if (security != null) {
1480 security.checkWrite(path);
1482 return fs.setPermission(this, FileSystem.ACCESS_READ, readable, ownerOnly);
1486 * A convenience method to set the owner's read permission for this abstract
1489 * <p>An invocation of this method of the form <tt>file.setReadable(arg)</tt>
1490 * behaves in exactly the same way as the invocation
1493 * file.setReadable(arg, true) </pre>
1496 * If <code>true</code>, sets the access permission to allow read
1497 * operations; if <code>false</code> to disallow read operations
1499 * @return <code>true</code> if and only if the operation succeeded. The
1500 * operation will fail if the user does not have permission to
1501 * change the access permissions of this abstract pathname. If
1502 * <code>readable</code> is <code>false</code> and the underlying
1503 * file system does not implement a read permission, then the
1504 * operation will fail.
1506 * @throws SecurityException
1507 * If a security manager exists and its <code>{@link
1508 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1509 * method denies write access to the file
1513 public boolean setReadable(boolean readable) {
1514 return setReadable(readable, true);
1518 * Sets the owner's or everybody's execute permission for this abstract
1521 * <p> The {@link java.nio.file.Files} class defines methods that operate on
1522 * file attributes including file permissions. This may be used when finer
1523 * manipulation of file permissions is required.
1526 * If <code>true</code>, sets the access permission to allow execute
1527 * operations; if <code>false</code> to disallow execute operations
1530 * If <code>true</code>, the execute permission applies only to the
1531 * owner's execute permission; otherwise, it applies to everybody.
1532 * If the underlying file system can not distinguish the owner's
1533 * execute permission from that of others, then the permission will
1534 * apply to everybody, regardless of this value.
1536 * @return <code>true</code> if and only if the operation succeeded. The
1537 * operation will fail if the user does not have permission to
1538 * change the access permissions of this abstract pathname. If
1539 * <code>executable</code> is <code>false</code> and the underlying
1540 * file system does not implement an execute permission, then the
1541 * operation will fail.
1543 * @throws SecurityException
1544 * If a security manager exists and its <code>{@link
1545 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1546 * method denies write access to the file
1550 public boolean setExecutable(boolean executable, boolean ownerOnly) {
1551 SecurityManager security = System.getSecurityManager();
1552 if (security != null) {
1553 security.checkWrite(path);
1555 return fs.setPermission(this, FileSystem.ACCESS_EXECUTE, executable, ownerOnly);
1559 * A convenience method to set the owner's execute permission for this abstract
1562 * <p>An invocation of this method of the form <tt>file.setExcutable(arg)</tt>
1563 * behaves in exactly the same way as the invocation
1566 * file.setExecutable(arg, true) </pre>
1569 * If <code>true</code>, sets the access permission to allow execute
1570 * operations; if <code>false</code> to disallow execute operations
1572 * @return <code>true</code> if and only if the operation succeeded. The
1573 * operation will fail if the user does not have permission to
1574 * change the access permissions of this abstract pathname. If
1575 * <code>executable</code> is <code>false</code> and the underlying
1576 * file system does not implement an excute permission, then the
1577 * operation will fail.
1579 * @throws SecurityException
1580 * If a security manager exists and its <code>{@link
1581 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1582 * method denies write access to the file
1586 public boolean setExecutable(boolean executable) {
1587 return setExecutable(executable, true);
1591 * Tests whether the application can execute the file denoted by this
1592 * abstract pathname.
1594 * @return <code>true</code> if and only if the abstract pathname exists
1595 * <em>and</em> the application is allowed to execute the file
1597 * @throws SecurityException
1598 * If a security manager exists and its <code>{@link
1599 * java.lang.SecurityManager#checkExec(java.lang.String)}</code>
1600 * method denies execute access to the file
1604 public boolean canExecute() {
1605 SecurityManager security = System.getSecurityManager();
1606 if (security != null) {
1607 security.checkExec(path);
1609 return fs.checkAccess(this, FileSystem.ACCESS_EXECUTE);
1613 /* -- Filesystem interface -- */
1616 * List the available filesystem roots.
1618 * <p> A particular Java platform may support zero or more
1619 * hierarchically-organized file systems. Each file system has a
1620 * {@code root} directory from which all other files in that file system
1621 * can be reached. Windows platforms, for example, have a root directory
1622 * for each active drive; UNIX platforms have a single root directory,
1623 * namely {@code "/"}. The set of available filesystem roots is affected
1624 * by various system-level operations such as the insertion or ejection of
1625 * removable media and the disconnecting or unmounting of physical or
1626 * virtual disk drives.
1628 * <p> This method returns an array of {@code File} objects that denote the
1629 * root directories of the available filesystem roots. It is guaranteed
1630 * that the canonical pathname of any file physically present on the local
1631 * machine will begin with one of the roots returned by this method.
1633 * <p> The canonical pathname of a file that resides on some other machine
1634 * and is accessed via a remote-filesystem protocol such as SMB or NFS may
1635 * or may not begin with one of the roots returned by this method. If the
1636 * pathname of a remote file is syntactically indistinguishable from the
1637 * pathname of a local file then it will begin with one of the roots
1638 * returned by this method. Thus, for example, {@code File} objects
1639 * denoting the root directories of the mapped network drives of a Windows
1640 * platform will be returned by this method, while {@code File} objects
1641 * containing UNC pathnames will not be returned by this method.
1643 * <p> Unlike most methods in this class, this method does not throw
1644 * security exceptions. If a security manager exists and its {@link
1645 * SecurityManager#checkRead(String)} method denies read access to a
1646 * particular root directory, then that directory will not appear in the
1649 * @return An array of {@code File} objects denoting the available
1650 * filesystem roots, or {@code null} if the set of roots could not
1651 * be determined. The array will be empty if there are no
1655 * @see java.nio.file.FileStore
1657 public static File[] listRoots() {
1658 return fs.listRoots();
1662 /* -- Disk usage -- */
1665 * Returns the size of the partition <a href="#partName">named</a> by this
1666 * abstract pathname.
1668 * @return The size, in bytes, of the partition or <tt>0L</tt> if this
1669 * abstract pathname does not name a partition
1671 * @throws SecurityException
1672 * If a security manager has been installed and it denies
1673 * {@link RuntimePermission}<tt>("getFileSystemAttributes")</tt>
1674 * or its {@link SecurityManager#checkRead(String)} method denies
1675 * read access to the file named by this abstract pathname
1679 public long getTotalSpace() {
1680 SecurityManager sm = System.getSecurityManager();
1682 sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
1685 return fs.getSpace(this, FileSystem.SPACE_TOTAL);
1689 * Returns the number of unallocated bytes in the partition <a
1690 * href="#partName">named</a> by this abstract path name.
1692 * <p> The returned number of unallocated bytes is a hint, but not
1693 * a guarantee, that it is possible to use most or any of these
1694 * bytes. The number of unallocated bytes is most likely to be
1695 * accurate immediately after this call. It is likely to be made
1696 * inaccurate by any external I/O operations including those made
1697 * on the system outside of this virtual machine. This method
1698 * makes no guarantee that write operations to this file system
1701 * @return The number of unallocated bytes on the partition <tt>0L</tt>
1702 * if the abstract pathname does not name a partition. This
1703 * value will be less than or equal to the total file system size
1704 * returned by {@link #getTotalSpace}.
1706 * @throws SecurityException
1707 * If a security manager has been installed and it denies
1708 * {@link RuntimePermission}<tt>("getFileSystemAttributes")</tt>
1709 * or its {@link SecurityManager#checkRead(String)} method denies
1710 * read access to the file named by this abstract pathname
1714 public long getFreeSpace() {
1715 SecurityManager sm = System.getSecurityManager();
1717 sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
1720 return fs.getSpace(this, FileSystem.SPACE_FREE);
1724 * Returns the number of bytes available to this virtual machine on the
1725 * partition <a href="#partName">named</a> by this abstract pathname. When
1726 * possible, this method checks for write permissions and other operating
1727 * system restrictions and will therefore usually provide a more accurate
1728 * estimate of how much new data can actually be written than {@link
1731 * <p> The returned number of available bytes is a hint, but not a
1732 * guarantee, that it is possible to use most or any of these bytes. The
1733 * number of unallocated bytes is most likely to be accurate immediately
1734 * after this call. It is likely to be made inaccurate by any external
1735 * I/O operations including those made on the system outside of this
1736 * virtual machine. This method makes no guarantee that write operations
1737 * to this file system will succeed.
1739 * @return The number of available bytes on the partition or <tt>0L</tt>
1740 * if the abstract pathname does not name a partition. On
1741 * systems where this information is not available, this method
1742 * will be equivalent to a call to {@link #getFreeSpace}.
1744 * @throws SecurityException
1745 * If a security manager has been installed and it denies
1746 * {@link RuntimePermission}<tt>("getFileSystemAttributes")</tt>
1747 * or its {@link SecurityManager#checkRead(String)} method denies
1748 * read access to the file named by this abstract pathname
1752 public long getUsableSpace() {
1753 SecurityManager sm = System.getSecurityManager();
1755 sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
1758 return fs.getSpace(this, FileSystem.SPACE_USABLE);
1761 /* -- Temporary files -- */
1763 private static class TempDirectory {
1764 private TempDirectory() { }
1766 // temporary directory location
1767 private static final File tmpdir = new File(fs.normalize(AccessController
1768 .doPrivileged(new GetPropertyAction("java.io.tmpdir"))));
1769 static File location() {
1773 // file name generation
1774 private static final SecureRandom random = new SecureRandom();
1775 static File generateFile(String prefix, String suffix, File dir) {
1776 long n = random.nextLong();
1777 if (n == Long.MIN_VALUE) {
1778 n = 0; // corner case
1782 return new File(dir, prefix + Long.toString(n) + suffix);
1787 * <p> Creates a new empty file in the specified directory, using the
1788 * given prefix and suffix strings to generate its name. If this method
1789 * returns successfully then it is guaranteed that:
1792 * <li> The file denoted by the returned abstract pathname did not exist
1793 * before this method was invoked, and
1794 * <li> Neither this method nor any of its variants will return the same
1795 * abstract pathname again in the current invocation of the virtual
1799 * This method provides only part of a temporary-file facility. To arrange
1800 * for a file created by this method to be deleted automatically, use the
1801 * <code>{@link #deleteOnExit}</code> method.
1803 * <p> The <code>prefix</code> argument must be at least three characters
1804 * long. It is recommended that the prefix be a short, meaningful string
1805 * such as <code>"hjb"</code> or <code>"mail"</code>. The
1806 * <code>suffix</code> argument may be <code>null</code>, in which case the
1807 * suffix <code>".tmp"</code> will be used.
1809 * <p> To create the new file, the prefix and the suffix may first be
1810 * adjusted to fit the limitations of the underlying platform. If the
1811 * prefix is too long then it will be truncated, but its first three
1812 * characters will always be preserved. If the suffix is too long then it
1813 * too will be truncated, but if it begins with a period character
1814 * (<code>'.'</code>) then the period and the first three characters
1815 * following it will always be preserved. Once these adjustments have been
1816 * made the name of the new file will be generated by concatenating the
1817 * prefix, five or more internally-generated characters, and the suffix.
1819 * <p> If the <code>directory</code> argument is <code>null</code> then the
1820 * system-dependent default temporary-file directory will be used. The
1821 * default temporary-file directory is specified by the system property
1822 * <code>java.io.tmpdir</code>. On UNIX systems the default value of this
1823 * property is typically <code>"/tmp"</code> or <code>"/var/tmp"</code>; on
1824 * Microsoft Windows systems it is typically <code>"C:\\WINNT\\TEMP"</code>. A different
1825 * value may be given to this system property when the Java virtual machine
1826 * is invoked, but programmatic changes to this property are not guaranteed
1827 * to have any effect upon the temporary directory used by this method.
1829 * @param prefix The prefix string to be used in generating the file's
1830 * name; must be at least three characters long
1832 * @param suffix The suffix string to be used in generating the file's
1833 * name; may be <code>null</code>, in which case the
1834 * suffix <code>".tmp"</code> will be used
1836 * @param directory The directory in which the file is to be created, or
1837 * <code>null</code> if the default temporary-file
1838 * directory is to be used
1840 * @return An abstract pathname denoting a newly-created empty file
1842 * @throws IllegalArgumentException
1843 * If the <code>prefix</code> argument contains fewer than three
1846 * @throws IOException If a file could not be created
1848 * @throws SecurityException
1849 * If a security manager exists and its <code>{@link
1850 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1851 * method does not allow a file to be created
1855 public static File createTempFile(String prefix, String suffix,
1859 if (prefix.length() < 3)
1860 throw new IllegalArgumentException("Prefix string too short");
1864 File tmpdir = (directory != null) ? directory : TempDirectory.location();
1865 SecurityManager sm = System.getSecurityManager();
1868 f = TempDirectory.generateFile(prefix, suffix, tmpdir);
1871 sm.checkWrite(f.getPath());
1872 } catch (SecurityException se) {
1873 // don't reveal temporary directory location
1874 if (directory == null)
1875 throw new SecurityException("Unable to create temporary file");
1879 } while (!fs.createFileExclusively(f.getPath()));
1884 * Creates an empty file in the default temporary-file directory, using
1885 * the given prefix and suffix to generate its name. Invoking this method
1886 * is equivalent to invoking <code>{@link #createTempFile(java.lang.String,
1887 * java.lang.String, java.io.File)
1888 * createTempFile(prefix, suffix, null)}</code>.
1891 * java.nio.file.Files#createTempFile(String,String,java.nio.file.attribute.FileAttribute[])
1892 * Files.createTempFile} method provides an alternative method to create an
1893 * empty file in the temporary-file directory. Files created by that method
1894 * may have more restrictive access permissions to files created by this
1895 * method and so may be more suited to security-sensitive applications.
1897 * @param prefix The prefix string to be used in generating the file's
1898 * name; must be at least three characters long
1900 * @param suffix The suffix string to be used in generating the file's
1901 * name; may be <code>null</code>, in which case the
1902 * suffix <code>".tmp"</code> will be used
1904 * @return An abstract pathname denoting a newly-created empty file
1906 * @throws IllegalArgumentException
1907 * If the <code>prefix</code> argument contains fewer than three
1910 * @throws IOException If a file could not be created
1912 * @throws SecurityException
1913 * If a security manager exists and its <code>{@link
1914 * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1915 * method does not allow a file to be created
1918 * @see java.nio.file.Files#createTempDirectory(String,FileAttribute[])
1920 public static File createTempFile(String prefix, String suffix)
1923 return createTempFile(prefix, suffix, null);
1926 /* -- Basic infrastructure -- */
1929 * Compares two abstract pathnames lexicographically. The ordering
1930 * defined by this method depends upon the underlying system. On UNIX
1931 * systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows
1932 * systems it is not.
1934 * @param pathname The abstract pathname to be compared to this abstract
1937 * @return Zero if the argument is equal to this abstract pathname, a
1938 * value less than zero if this abstract pathname is
1939 * lexicographically less than the argument, or a value greater
1940 * than zero if this abstract pathname is lexicographically
1941 * greater than the argument
1945 public int compareTo(File pathname) {
1946 return fs.compare(this, pathname);
1950 * Tests this abstract pathname for equality with the given object.
1951 * Returns <code>true</code> if and only if the argument is not
1952 * <code>null</code> and is an abstract pathname that denotes the same file
1953 * or directory as this abstract pathname. Whether or not two abstract
1954 * pathnames are equal depends upon the underlying system. On UNIX
1955 * systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows
1956 * systems it is not.
1958 * @param obj The object to be compared with this abstract pathname
1960 * @return <code>true</code> if and only if the objects are the same;
1961 * <code>false</code> otherwise
1963 public boolean equals(Object obj) {
1964 if ((obj != null) && (obj instanceof File)) {
1965 return compareTo((File)obj) == 0;
1971 * Computes a hash code for this abstract pathname. Because equality of
1972 * abstract pathnames is inherently system-dependent, so is the computation
1973 * of their hash codes. On UNIX systems, the hash code of an abstract
1974 * pathname is equal to the exclusive <em>or</em> of the hash code
1975 * of its pathname string and the decimal value
1976 * <code>1234321</code>. On Microsoft Windows systems, the hash
1977 * code is equal to the exclusive <em>or</em> of the hash code of
1978 * its pathname string converted to lower case and the decimal
1979 * value <code>1234321</code>. Locale is not taken into account on
1980 * lowercasing the pathname string.
1982 * @return A hash code for this abstract pathname
1984 public int hashCode() {
1985 return fs.hashCode(this);
1989 * Returns the pathname string of this abstract pathname. This is just the
1990 * string returned by the <code>{@link #getPath}</code> method.
1992 * @return The string form of this abstract pathname
1994 public String toString() {
1999 * WriteObject is called to save this filename.
2000 * The separator character is saved also so it can be replaced
2001 * in case the path is reconstituted on a different host type.
2003 * @serialData Default fields followed by separator character.
2005 private synchronized void writeObject(java.io.ObjectOutputStream s)
2008 s.defaultWriteObject();
2009 s.writeChar(this.separatorChar); // Add the separator character
2013 * readObject is called to restore this filename.
2014 * The original separator character is read. If it is different
2015 * than the separator character on this system, then the old separator
2016 * is replaced by the local separator.
2018 private synchronized void readObject(java.io.ObjectInputStream s)
2019 throws IOException, ClassNotFoundException
2021 ObjectInputStream.GetField fields = s.readFields();
2022 String pathField = (String)fields.get("path", null);
2023 char sep = s.readChar(); // read the previous separator char
2024 if (sep != separatorChar)
2025 pathField = pathField.replace(sep, separatorChar);
2026 this.path = fs.normalize(pathField);
2027 this.prefixLength = fs.prefixLength(this.path);
2030 /** use serialVersionUID from JDK 1.0.2 for interoperability */
2031 private static final long serialVersionUID = 301077366599181567L;
2033 // -- Integration with java.nio.file --
2035 private volatile transient Path filePath;
2038 * Returns a {@link Path java.nio.file.Path} object constructed from the
2039 * this abstract path. The resulting {@code Path} is associated with the
2040 * {@link java.nio.file.FileSystems#getDefault default-filesystem}.
2042 * <p> The first invocation of this method works as if invoking it were
2043 * equivalent to evaluating the expression:
2045 * {@link java.nio.file.FileSystems#getDefault FileSystems.getDefault}().{@link
2046 * java.nio.file.FileSystem#getPath getPath}(this.{@link #getPath getPath}());
2047 * </pre></blockquote>
2048 * Subsequent invocations of this method return the same {@code Path}.
2050 * <p> If this abstract pathname is the empty abstract pathname then this
2051 * method returns a {@code Path} that may be used to access the current
2054 * @return a {@code Path} constructed from this abstract path
2056 * @throws java.nio.file.InvalidPathException
2057 * if a {@code Path} object cannot be constructed from the abstract
2058 * path (see {@link java.nio.file.FileSystem#getPath FileSystem.getPath})
2063 public Path toPath() {
2064 Path result = filePath;
2065 if (result == null) {
2066 synchronized (this) {
2068 if (result == null) {
2069 result = FileSystems.getDefault().getPath(path);