1 /* 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. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.io; 27 28 import java.net.URI; 29 import java.net.URL; 30 import java.net.MalformedURLException; 31 import java.net.URISyntaxException; 32 import java.util.List; 33 import java.util.ArrayList; 34 import java.security.AccessController; 35 import java.security.SecureRandom; 36 import java.nio.file.Path; 37 import java.nio.file.FileSystems; 38 import sun.security.action.GetPropertyAction; 39 40 /** 41 * An abstract representation of file and directory pathnames. 42 * 43 * <p> User interfaces and operating systems use system-dependent <em>pathname 44 * strings</em> to name files and directories. This class presents an 45 * abstract, system-independent view of hierarchical pathnames. An 46 * <em>abstract pathname</em> has two components: 47 * 48 * <ol> 49 * <li> An optional system-dependent <em>prefix</em> string, 50 * such as a disk-drive specifier, <code>"/"</code> 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>. 53 * </ol> 54 * 55 * The first name in an abstract pathname may be a directory name or, in the 56 * case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name 57 * in an abstract pathname denotes a directory; the last name may denote 58 * either a directory or a file. The <em>empty</em> abstract pathname has no 59 * prefix and an empty name sequence. 60 * 61 * <p> The conversion of a pathname string to or from an abstract pathname is 62 * inherently system-dependent. When an abstract pathname is converted into a 63 * pathname string, each name is separated from the next by a single copy of 64 * the default <em>separator character</em>. The default name-separator 65 * character is defined by the system property <code>file.separator</code>, and 66 * is made available in the public static fields <code>{@link 67 * #separator}</code> and <code>{@link #separatorChar}</code> of this class. 68 * When a pathname string is converted into an abstract pathname, the names 69 * within it may be separated by the default name-separator character or by any 70 * other name-separator character that is supported by the underlying system. 71 * 72 * <p> A pathname, whether abstract or in string form, may be either 73 * <em>absolute</em> or <em>relative</em>. An absolute pathname is complete in 74 * that no other information is required in order to locate the file that it 75 * denotes. A relative pathname, in contrast, must be interpreted in terms of 76 * information taken from some other pathname. By default the classes in the 77 * <code>java.io</code> package always resolve relative pathnames against the 78 * current user directory. This directory is named by the system property 79 * <code>user.dir</code>, and is typically the directory in which the Java 80 * virtual machine was invoked. 81 * 82 * <p> The <em>parent</em> of an abstract pathname may be obtained by invoking 83 * the {@link #getParent} method of this class and consists of the pathname's 84 * prefix and each name in the pathname's name sequence except for the last. 85 * Each directory's absolute pathname is an ancestor of any <tt>File</tt> 86 * object with an absolute abstract pathname which begins with the directory's 87 * absolute pathname. For example, the directory denoted by the abstract 88 * pathname <tt>"/usr"</tt> is an ancestor of the directory denoted by the 89 * pathname <tt>"/usr/local/bin"</tt>. 90 * 91 * <p> The prefix concept is used to handle root directories on UNIX platforms, 92 * and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms, 93 * as follows: 94 * 95 * <ul> 96 * 97 * <li> For UNIX platforms, the prefix of an absolute pathname is always 98 * <code>"/"</code>. Relative pathnames have no prefix. The abstract pathname 99 * denoting the root directory has the prefix <code>"/"</code> and an empty 100 * name sequence. 101 * 102 * <li> For Microsoft Windows platforms, the prefix of a pathname that contains a drive 103 * specifier consists of the drive letter followed by <code>":"</code> and 104 * possibly followed by <code>"\\"</code> if the pathname is absolute. The 105 * prefix of a UNC pathname is <code>"\\\\"</code>; the hostname and the share 106 * name are the first two names in the name sequence. A relative pathname that 107 * does not specify a drive has no prefix. 108 * 109 * </ul> 110 * 111 * <p> Instances of this class may or may not denote an actual file-system 112 * object such as a file or a directory. If it does denote such an object 113 * then that object resides in a <i>partition</i>. A partition is an 114 * operating system-specific portion of storage for a file system. A single 115 * storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may 116 * contain multiple partitions. The object, if any, will reside on the 117 * partition <a name="partName">named</a> by some ancestor of the absolute 118 * form of this pathname. 119 * 120 * <p> A file system may implement restrictions to certain operations on the 121 * actual file-system object, such as reading, writing, and executing. These 122 * restrictions are collectively known as <i>access permissions</i>. The file 123 * system may have multiple sets of access permissions on a single object. 124 * For example, one set may apply to the object's <i>owner</i>, and another 125 * may apply to all other users. The access permissions on an object may 126 * cause some methods in this class to fail. 127 * 128 * <p> Instances of the <code>File</code> class are immutable; that is, once 129 * created, the abstract pathname represented by a <code>File</code> object 130 * will never change. 131 * 132 * <h4>Interoperability with {@code java.nio.file} package</h4> 133 * 134 * <p> The <a href="../../java/nio/file/package-summary.html">{@code java.nio.file}</a> 135 * package defines interfaces and classes for the Java virtual machine to access 136 * files, file attributes, and file systems. This API may be used to overcome 137 * many of the limitations of the {@code java.io.File} class. 138 * The {@link #toPath toPath} method may be used to obtain a {@link 139 * Path} that uses the abstract path represented by a {@code File} object to 140 * locate a file. The resulting {@code Path} may be used with the {@link 141 * java.nio.file.Files} class to provide more efficient and extensive access to 142 * additional file operations, file attributes, and I/O exceptions to help 143 * diagnose errors when an operation on a file fails. 144 * 145 * @author unascribed 146 * @since JDK1.0 147 */ 148 149 public class File 150 implements Serializable, Comparable<File> 151 { 152 153 /** 154 * The FileSystem object representing the platform's local file system. 155 */ 156 static private FileSystem fs = FileSystem.getFileSystem(); 157 158 /** 159 * This abstract pathname's normalized pathname string. A normalized 160 * pathname string uses the default name-separator character and does not 161 * contain any duplicate or redundant separators. 162 * 163 * @serial 164 */ 165 private String path; 166 167 /** 168 * The length of this abstract pathname's prefix, or zero if it has no 169 * prefix. 170 */ 171 private transient int prefixLength; 172 173 /** 174 * Returns the length of this abstract pathname's prefix. 175 * For use by FileSystem classes. 176 */ 177 int getPrefixLength() { 178 return prefixLength; 179 } 180 181 /** 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>. 186 * 187 * @see java.lang.System#getProperty(java.lang.String) 188 */ 189 public static final char separatorChar = fs.getSeparator(); 190 191 /** 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>. 195 */ 196 public static final String separator = "" + separatorChar; 197 198 /** 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>. 205 * 206 * @see java.lang.System#getProperty(java.lang.String) 207 */ 208 public static final char pathSeparatorChar = fs.getPathSeparator(); 209 210 /** 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>. 214 */ 215 public static final String pathSeparator = "" + pathSeparatorChar; 216 217 218 /* -- Constructors -- */ 219 220 /** 221 * Internal constructor for already-normalized pathname strings. 222 */ 223 private File(String pathname, int prefixLength) { 224 this.path = pathname; 225 this.prefixLength = prefixLength; 226 } 227 228 /** 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. 232 */ 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; 238 } 239 240 /** 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. 244 * 245 * @param pathname A pathname string 246 * @throws NullPointerException 247 * If the <code>pathname</code> argument is <code>null</code> 248 */ 249 public File(String pathname) { 250 if (pathname == null) { 251 throw new NullPointerException(); 252 } 253 this.path = fs.normalize(pathname); 254 this.prefixLength = fs.prefixLength(this.path); 255 } 256 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. */ 263 264 /** 265 * Creates a new <code>File</code> instance from a parent pathname string 266 * and a child pathname string. 267 * 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. 272 * 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. 283 * 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> 288 */ 289 public File(String parent, String child) { 290 if (child == null) { 291 throw new NullPointerException(); 292 } 293 if (parent != null) { 294 if (parent.equals("")) { 295 this.path = fs.resolve(fs.getDefaultParent(), 296 fs.normalize(child)); 297 } else { 298 this.path = fs.resolve(fs.normalize(parent), 299 fs.normalize(child)); 300 } 301 } else { 302 this.path = fs.normalize(child); 303 } 304 this.prefixLength = fs.prefixLength(this.path); 305 } 306 307 /** 308 * Creates a new <code>File</code> instance from a parent abstract 309 * pathname and a child pathname string. 310 * 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. 315 * 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. 326 * 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> 331 */ 332 public File(File parent, String child) { 333 if (child == null) { 334 throw new NullPointerException(); 335 } 336 if (parent != null) { 337 if (parent.path.equals("")) { 338 this.path = fs.resolve(fs.getDefaultParent(), 339 fs.normalize(child)); 340 } else { 341 this.path = fs.resolve(parent.path, 342 fs.normalize(child)); 343 } 344 } else { 345 this.path = fs.normalize(child); 346 } 347 this.prefixLength = fs.prefixLength(this.path); 348 } 349 350 /** 351 * Creates a new <tt>File</tt> instance by converting the given 352 * <tt>file:</tt> URI into an abstract pathname. 353 * 354 * <p> The exact form of a <tt>file:</tt> URI is system-dependent, hence 355 * the transformation performed by this constructor is also 356 * system-dependent. 357 * 358 * <p> For a given abstract pathname <i>f</i> it is guaranteed that 359 * 360 * <blockquote><tt> 361 * new File(</tt><i> f</i><tt>.{@link #toURI() toURI}()).equals(</tt><i> f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}()) 362 * </tt></blockquote> 363 * 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. 370 * 371 * @param uri 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 375 * 376 * @throws NullPointerException 377 * If <tt>uri</tt> is <tt>null</tt> 378 * 379 * @throws IllegalArgumentException 380 * If the preconditions on the parameter do not hold 381 * 382 * @see #toURI() 383 * @see java.net.URI 384 * @since 1.4 385 */ 386 public File(URI uri) { 387 388 // Check our many preconditions 389 if (!uri.isAbsolute()) 390 throw new IllegalArgumentException("URI is not absolute"); 391 if (uri.isOpaque()) 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(); 403 if (p.equals("")) 404 throw new IllegalArgumentException("URI path component is empty"); 405 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); 412 } 413 414 415 /* -- Path-component accessors -- */ 416 417 /** 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. 422 * 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 425 * is empty 426 */ 427 public String getName() { 428 int index = path.lastIndexOf(separatorChar); 429 if (index < prefixLength) return path.substring(prefixLength); 430 return path.substring(index + 1); 431 } 432 433 /** 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. 436 * 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. 441 * 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 445 */ 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); 451 return null; 452 } 453 return path.substring(0, index); 454 } 455 456 /** 457 * Returns the abstract pathname of this abstract pathname's parent, 458 * or <code>null</code> if this pathname does not name a parent 459 * directory. 460 * 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. 465 * 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 469 * 470 * @since 1.2 471 */ 472 public File getParentFile() { 473 String p = this.getParent(); 474 if (p == null) return null; 475 return new File(p, this.prefixLength); 476 } 477 478 /** 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. 482 * 483 * @return The string form of this abstract pathname 484 */ 485 public String getPath() { 486 return path; 487 } 488 489 490 /* -- Path operations -- */ 491 492 /** 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>. 498 * 499 * @return <code>true</code> if this abstract pathname is absolute, 500 * <code>false</code> otherwise 501 */ 502 public boolean isAbsolute() { 503 return fs.isAbsolute(this); 504 } 505 506 /** 507 * Returns the absolute pathname string of this abstract pathname. 508 * 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 519 * directory. 520 * 521 * @return The absolute pathname string denoting the same file or 522 * directory as this abstract pathname 523 * 524 * @throws SecurityException 525 * If a required system property value cannot be accessed. 526 * 527 * @see java.io.File#isAbsolute() 528 */ 529 public String getAbsolutePath() { 530 return fs.resolve(this); 531 } 532 533 /** 534 * Returns the absolute form of this abstract pathname. Equivalent to 535 * <code>new File(this.{@link #getAbsolutePath})</code>. 536 * 537 * @return The absolute abstract pathname denoting the same file or 538 * directory as this abstract pathname 539 * 540 * @throws SecurityException 541 * If a required system property value cannot be accessed. 542 * 543 * @since 1.2 544 */ 545 public File getAbsoluteFile() { 546 String absPath = getAbsolutePath(); 547 return new File(absPath, fs.prefixLength(absPath)); 548 } 549 550 /** 551 * Returns the canonical pathname string of this abstract pathname. 552 * 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). 561 * 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. 570 * 571 * @return The canonical pathname string denoting the same file or 572 * directory as this abstract pathname 573 * 574 * @throws IOException 575 * If an I/O error occurs, which is possible because the 576 * construction of the canonical pathname may require 577 * filesystem queries 578 * 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 584 * 585 * @since JDK1.1 586 * @see Path#toRealPath 587 */ 588 public String getCanonicalPath() throws IOException { 589 return fs.canonicalize(fs.resolve(this)); 590 } 591 592 /** 593 * Returns the canonical form of this abstract pathname. Equivalent to 594 * <code>new File(this.{@link #getCanonicalPath})</code>. 595 * 596 * @return The canonical pathname string denoting the same file or 597 * directory as this abstract pathname 598 * 599 * @throws IOException 600 * If an I/O error occurs, which is possible because the 601 * construction of the canonical pathname may require 602 * filesystem queries 603 * 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 609 * 610 * @since 1.2 611 * @see Path#toRealPath 612 */ 613 public File getCanonicalFile() throws IOException { 614 String canonPath = getCanonicalPath(); 615 return new File(canonPath, fs.prefixLength(canonPath)); 616 } 617 618 private static String slashify(String path, boolean isDirectory) { 619 String p = path; 620 if (File.separatorChar != '/') 621 p = p.replace(File.separatorChar, '/'); 622 if (!p.startsWith("/")) 623 p = "/" + p; 624 if (!p.endsWith("/") && isDirectory) 625 p = p + "/"; 626 return p; 627 } 628 629 /** 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. 634 * 635 * @return A URL object representing the equivalent file URL 636 * 637 * @throws MalformedURLException 638 * If the path cannot be parsed as a URL 639 * 640 * @see #toURI() 641 * @see java.net.URI 642 * @see java.net.URI#toURL() 643 * @see java.net.URL 644 * @since 1.2 645 * 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. 651 */ 652 @Deprecated 653 public URL toURL() throws MalformedURLException { 654 return new URL("file", "", slashify(getAbsolutePath(), isDirectory())); 655 } 656 657 /** 658 * Constructs a <tt>file:</tt> URI that represents this abstract pathname. 659 * 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. 663 * 664 * <p> For a given abstract pathname <i>f</i>, it is guaranteed that 665 * 666 * <blockquote><tt> 667 * new {@link #File(java.net.URI) File}(</tt><i> f</i><tt>.toURI()).equals(</tt><i> f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}()) 668 * </tt></blockquote> 669 * 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. 677 * 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. 685 * 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 690 * be accessed. 691 * 692 * @see #File(java.net.URI) 693 * @see java.net.URI 694 * @see java.net.URI#toURL() 695 * @since 1.4 696 */ 697 public URI toURI() { 698 try { 699 File f = getAbsoluteFile(); 700 String sp = slashify(f.getPath(), f.isDirectory()); 701 if (sp.startsWith("//")) 702 sp = "//" + sp; 703 return new URI("file", null, sp, null); 704 } catch (URISyntaxException x) { 705 throw new Error(x); // Can't happen 706 } 707 } 708 709 710 /* -- Attribute accessors -- */ 711 712 /** 713 * Tests whether the application can read the file denoted by this 714 * abstract pathname. 715 * 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 719 * 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 724 */ 725 public boolean canRead() { 726 SecurityManager security = System.getSecurityManager(); 727 if (security != null) { 728 security.checkRead(path); 729 } 730 return fs.checkAccess(this, FileSystem.ACCESS_READ); 731 } 732 733 /** 734 * Tests whether the application can modify the file denoted by this 735 * abstract pathname. 736 * 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. 741 * 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 746 */ 747 public boolean canWrite() { 748 SecurityManager security = System.getSecurityManager(); 749 if (security != null) { 750 security.checkWrite(path); 751 } 752 return fs.checkAccess(this, FileSystem.ACCESS_WRITE); 753 } 754 755 /** 756 * Tests whether the file or directory denoted by this abstract pathname 757 * exists. 758 * 759 * @return <code>true</code> if and only if the file or directory denoted 760 * by this abstract pathname exists; <code>false</code> otherwise 761 * 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 766 */ 767 public boolean exists() { 768 SecurityManager security = System.getSecurityManager(); 769 if (security != null) { 770 security.checkRead(path); 771 } 772 return ((fs.getBooleanAttributes(this) & FileSystem.BA_EXISTS) != 0); 773 } 774 775 /** 776 * Tests whether the file denoted by this abstract pathname is a 777 * directory. 778 * 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. 784 * 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 788 * 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 793 */ 794 public boolean isDirectory() { 795 SecurityManager security = System.getSecurityManager(); 796 if (security != null) { 797 security.checkRead(path); 798 } 799 return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY) 800 != 0); 801 } 802 803 /** 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. 808 * 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. 814 * 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 818 * 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 823 */ 824 public boolean isFile() { 825 SecurityManager security = System.getSecurityManager(); 826 if (security != null) { 827 security.checkRead(path); 828 } 829 return ((fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0); 830 } 831 832 /** 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. 838 * 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 842 * 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 847 * 848 * @since 1.2 849 */ 850 public boolean isHidden() { 851 SecurityManager security = System.getSecurityManager(); 852 if (security != null) { 853 security.checkRead(path); 854 } 855 return ((fs.getBooleanAttributes(this) & FileSystem.BA_HIDDEN) != 0); 856 } 857 858 /** 859 * Returns the time that the file denoted by this abstract pathname was 860 * last modified. 861 * 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. 868 * 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 873 * 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 878 */ 879 public long lastModified() { 880 SecurityManager security = System.getSecurityManager(); 881 if (security != null) { 882 security.checkRead(path); 883 } 884 return fs.getLastModifiedTime(this); 885 } 886 887 /** 888 * Returns the length of the file denoted by this abstract pathname. 889 * The return value is unspecified if this pathname denotes a directory. 890 * 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. 896 * 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. 901 * 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 906 */ 907 public long length() { 908 SecurityManager security = System.getSecurityManager(); 909 if (security != null) { 910 security.checkRead(path); 911 } 912 return fs.getLength(this); 913 } 914 915 916 /* -- File operations -- */ 917 918 /** 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. 924 * <P> 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. 929 * 930 * @return <code>true</code> if the named file does not exist and was 931 * successfully created; <code>false</code> if the named file 932 * already exists 933 * 934 * @throws IOException 935 * If an I/O error occurred 936 * 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 941 * 942 * @since 1.2 943 */ 944 public boolean createNewFile() throws IOException { 945 SecurityManager security = System.getSecurityManager(); 946 if (security != null) security.checkWrite(path); 947 return fs.createFileExclusively(path); 948 } 949 950 /** 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. 954 * 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. 959 * 960 * @return <code>true</code> if and only if the file or directory is 961 * successfully deleted; <code>false</code> otherwise 962 * 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 967 */ 968 public boolean delete() { 969 SecurityManager security = System.getSecurityManager(); 970 if (security != null) { 971 security.checkDelete(path); 972 } 973 return fs.delete(this); 974 } 975 976 /** 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. 984 * 985 * <p> Once deletion has been requested, it is not possible to cancel the 986 * request. This method should therefore be used with care. 987 * 988 * <P> 989 * Note: this method should <i>not</i> be used for file-locking, as 990 * the resulting protocol cannot be made to work reliably. The 991 * {@link java.nio.channels.FileLock FileLock} 992 * facility should be used instead. 993 * 994 * @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 998 * 999 * @see #delete 1000 * 1001 * @since 1.2 1002 */ 1003 public void deleteOnExit() { 1004 SecurityManager security = System.getSecurityManager(); 1005 if (security != null) { 1006 security.checkDelete(path); 1007 } 1008 DeleteOnExitHook.add(path); 1009 } 1010 1011 /** 1012 * Returns an array of strings naming the files and directories in the 1013 * directory denoted by this abstract pathname. 1014 * 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 1020 * complete path. 1021 * 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. 1025 * 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. 1031 * 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 1036 * I/O error occurs. 1037 * 1038 * @throws SecurityException 1039 * If a security manager exists and its {@link 1040 * SecurityManager#checkRead(String)} method denies read access to 1041 * the directory 1042 */ 1043 public String[] list() { 1044 SecurityManager security = System.getSecurityManager(); 1045 if (security != null) { 1046 security.checkRead(path); 1047 } 1048 return fs.list(this); 1049 } 1050 1051 /** 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. 1062 * 1063 * @param filter 1064 * A filename filter 1065 * 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. 1072 * 1073 * @throws SecurityException 1074 * If a security manager exists and its {@link 1075 * SecurityManager#checkRead(String)} method denies read access to 1076 * the directory 1077 * 1078 * @see java.nio.file.Files#newDirectoryStream(Path,String) 1079 */ 1080 public String[] list(FilenameFilter filter) { 1081 String names[] = list(); 1082 if ((names == null) || (filter == null)) { 1083 return names; 1084 } 1085 List<String> v = new ArrayList<>(); 1086 for (int i = 0 ; i < names.length ; i++) { 1087 if (filter.accept(this, names[i])) { 1088 v.add(names[i]); 1089 } 1090 } 1091 return v.toArray(new String[v.size()]); 1092 } 1093 1094 /** 1095 * Returns an array of abstract pathnames denoting the files in the 1096 * directory denoted by this abstract pathname. 1097 * 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. 1108 * 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. 1112 * 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 1117 * directories. 1118 * 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. 1124 * 1125 * @throws SecurityException 1126 * If a security manager exists and its {@link 1127 * SecurityManager#checkRead(String)} method denies read access to 1128 * the directory 1129 * 1130 * @since 1.2 1131 */ 1132 public File[] listFiles() { 1133 String[] ss = list(); 1134 if (ss == null) return null; 1135 int n = ss.length; 1136 File[] fs = new File[n]; 1137 for (int i = 0; i < n; i++) { 1138 fs[i] = new File(ss[i], this); 1139 } 1140 return fs; 1141 } 1142 1143 /** 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. 1155 * 1156 * @param filter 1157 * A filename filter 1158 * 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. 1164 * 1165 * @throws SecurityException 1166 * If a security manager exists and its {@link 1167 * SecurityManager#checkRead(String)} method denies read access to 1168 * the directory 1169 * 1170 * @since 1.2 1171 * @see java.nio.file.Files#newDirectoryStream(Path,String) 1172 */ 1173 public File[] listFiles(FilenameFilter filter) { 1174 String ss[] = list(); 1175 if (ss == null) return null; 1176 ArrayList<File> files = new ArrayList<>(); 1177 for (String s : ss) 1178 if ((filter == null) || filter.accept(this, s)) 1179 files.add(new File(s, this)); 1180 return files.toArray(new File[files.size()]); 1181 } 1182 1183 /** 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. 1193 * 1194 * @param filter 1195 * A file filter 1196 * 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. 1202 * 1203 * @throws SecurityException 1204 * If a security manager exists and its {@link 1205 * SecurityManager#checkRead(String)} method denies read access to 1206 * the directory 1207 * 1208 * @since 1.2 1209 * @see java.nio.file.Files#newDirectoryStream(Path,java.nio.file.DirectoryStream.Filter) 1210 */ 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)) 1218 files.add(f); 1219 } 1220 return files.toArray(new File[files.size()]); 1221 } 1222 1223 /** 1224 * Creates the directory named by this abstract pathname. 1225 * 1226 * @return <code>true</code> if and only if the directory was 1227 * created; <code>false</code> otherwise 1228 * 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 1233 */ 1234 public boolean mkdir() { 1235 SecurityManager security = System.getSecurityManager(); 1236 if (security != null) { 1237 security.checkWrite(path); 1238 } 1239 return fs.createDirectory(this); 1240 } 1241 1242 /** 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. 1247 * 1248 * @return <code>true</code> if and only if the directory was created, 1249 * along with all necessary parent directories; <code>false</code> 1250 * otherwise 1251 * 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 1257 * the <code>{@link 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 1261 */ 1262 public boolean mkdirs() { 1263 if (exists()) { 1264 return false; 1265 } 1266 if (mkdir()) { 1267 return true; 1268 } 1269 File canonFile = null; 1270 try { 1271 canonFile = getCanonicalFile(); 1272 } catch (IOException e) { 1273 return false; 1274 } 1275 1276 File parent = canonFile.getParentFile(); 1277 return (parent != null && (parent.mkdirs() || parent.exists()) && 1278 canonFile.mkdir()); 1279 } 1280 1281 /** 1282 * Renames the file denoted by this abstract pathname. 1283 * 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. 1290 * 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. 1294 * 1295 * @param dest The new abstract pathname for the named file 1296 * 1297 * @return <code>true</code> if and only if the renaming succeeded; 1298 * <code>false</code> otherwise 1299 * 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 1304 * 1305 * @throws NullPointerException 1306 * If parameter <code>dest</code> is <code>null</code> 1307 */ 1308 public boolean renameTo(File dest) { 1309 SecurityManager security = System.getSecurityManager(); 1310 if (security != null) { 1311 security.checkWrite(path); 1312 security.checkWrite(dest.path); 1313 } 1314 return fs.rename(this, dest); 1315 } 1316 1317 /** 1318 * Sets the last-modified time of the file or directory named by this 1319 * abstract pathname. 1320 * 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. 1327 * 1328 * @param time The new last-modified time, measured in milliseconds since 1329 * the epoch (00:00:00 GMT, January 1, 1970) 1330 * 1331 * @return <code>true</code> if and only if the operation succeeded; 1332 * <code>false</code> otherwise 1333 * 1334 * @throws IllegalArgumentException If the argument is negative 1335 * 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 1340 * 1341 * @since 1.2 1342 */ 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); 1348 } 1349 return fs.setLastModifiedTime(this, time); 1350 } 1351 1352 /** 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. 1358 * 1359 * @return <code>true</code> if and only if the operation succeeded; 1360 * <code>false</code> otherwise 1361 * 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 1366 * 1367 * @since 1.2 1368 */ 1369 public boolean setReadOnly() { 1370 SecurityManager security = System.getSecurityManager(); 1371 if (security != null) { 1372 security.checkWrite(path); 1373 } 1374 return fs.setReadOnly(this); 1375 } 1376 1377 /** 1378 * Sets the owner's or everybody's write permission for this abstract 1379 * pathname. 1380 * 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. 1384 * 1385 * @param writable 1386 * If <code>true</code>, sets the access permission to allow write 1387 * operations; if <code>false</code> to disallow write operations 1388 * 1389 * @param ownerOnly 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. 1395 * 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. 1399 * 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 1404 * 1405 * @since 1.6 1406 */ 1407 public boolean setWritable(boolean writable, boolean ownerOnly) { 1408 SecurityManager security = System.getSecurityManager(); 1409 if (security != null) { 1410 security.checkWrite(path); 1411 } 1412 return fs.setPermission(this, FileSystem.ACCESS_WRITE, writable, ownerOnly); 1413 } 1414 1415 /** 1416 * A convenience method to set the owner's write permission for this abstract 1417 * pathname. 1418 * 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 1421 * 1422 * <pre> 1423 * file.setWritable(arg, true) </pre> 1424 * 1425 * @param writable 1426 * If <code>true</code>, sets the access permission to allow write 1427 * operations; if <code>false</code> to disallow write operations 1428 * 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. 1432 * 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 1437 * 1438 * @since 1.6 1439 */ 1440 public boolean setWritable(boolean writable) { 1441 return setWritable(writable, true); 1442 } 1443 1444 /** 1445 * Sets the owner's or everybody's read permission for this abstract 1446 * pathname. 1447 * 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. 1451 * 1452 * @param readable 1453 * If <code>true</code>, sets the access permission to allow read 1454 * operations; if <code>false</code> to disallow read operations 1455 * 1456 * @param ownerOnly 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. 1462 * 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. 1469 * 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 1474 * 1475 * @since 1.6 1476 */ 1477 public boolean setReadable(boolean readable, boolean ownerOnly) { 1478 SecurityManager security = System.getSecurityManager(); 1479 if (security != null) { 1480 security.checkWrite(path); 1481 } 1482 return fs.setPermission(this, FileSystem.ACCESS_READ, readable, ownerOnly); 1483 } 1484 1485 /** 1486 * A convenience method to set the owner's read permission for this abstract 1487 * pathname. 1488 * 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 1491 * 1492 * <pre> 1493 * file.setReadable(arg, true) </pre> 1494 * 1495 * @param readable 1496 * If <code>true</code>, sets the access permission to allow read 1497 * operations; if <code>false</code> to disallow read operations 1498 * 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. 1505 * 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 1510 * 1511 * @since 1.6 1512 */ 1513 public boolean setReadable(boolean readable) { 1514 return setReadable(readable, true); 1515 } 1516 1517 /** 1518 * Sets the owner's or everybody's execute permission for this abstract 1519 * pathname. 1520 * 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. 1524 * 1525 * @param executable 1526 * If <code>true</code>, sets the access permission to allow execute 1527 * operations; if <code>false</code> to disallow execute operations 1528 * 1529 * @param ownerOnly 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. 1535 * 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. 1542 * 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 1547 * 1548 * @since 1.6 1549 */ 1550 public boolean setExecutable(boolean executable, boolean ownerOnly) { 1551 SecurityManager security = System.getSecurityManager(); 1552 if (security != null) { 1553 security.checkWrite(path); 1554 } 1555 return fs.setPermission(this, FileSystem.ACCESS_EXECUTE, executable, ownerOnly); 1556 } 1557 1558 /** 1559 * A convenience method to set the owner's execute permission for this abstract 1560 * pathname. 1561 * 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 1564 * 1565 * <pre> 1566 * file.setExecutable(arg, true) </pre> 1567 * 1568 * @param executable 1569 * If <code>true</code>, sets the access permission to allow execute 1570 * operations; if <code>false</code> to disallow execute operations 1571 * 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. 1578 * 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 1583 * 1584 * @since 1.6 1585 */ 1586 public boolean setExecutable(boolean executable) { 1587 return setExecutable(executable, true); 1588 } 1589 1590 /** 1591 * Tests whether the application can execute the file denoted by this 1592 * abstract pathname. 1593 * 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 1596 * 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 1601 * 1602 * @since 1.6 1603 */ 1604 public boolean canExecute() { 1605 SecurityManager security = System.getSecurityManager(); 1606 if (security != null) { 1607 security.checkExec(path); 1608 } 1609 return fs.checkAccess(this, FileSystem.ACCESS_EXECUTE); 1610 } 1611 1612 1613 /* -- Filesystem interface -- */ 1614 1615 /** 1616 * List the available filesystem roots. 1617 * 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. 1627 * 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. 1632 * 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. 1642 * 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 1647 * result. 1648 * 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 1652 * filesystem roots. 1653 * 1654 * @since 1.2 1655 * @see java.nio.file.FileStore 1656 */ 1657 public static File[] listRoots() { 1658 return fs.listRoots(); 1659 } 1660 1661 1662 /* -- Disk usage -- */ 1663 1664 /** 1665 * Returns the size of the partition <a href="#partName">named</a> by this 1666 * abstract pathname. 1667 * 1668 * @return The size, in bytes, of the partition or <tt>0L</tt> if this 1669 * abstract pathname does not name a partition 1670 * 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 1676 * 1677 * @since 1.6 1678 */ 1679 public long getTotalSpace() { 1680 SecurityManager sm = System.getSecurityManager(); 1681 if (sm != null) { 1682 sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); 1683 sm.checkRead(path); 1684 } 1685 return fs.getSpace(this, FileSystem.SPACE_TOTAL); 1686 } 1687 1688 /** 1689 * Returns the number of unallocated bytes in the partition <a 1690 * href="#partName">named</a> by this abstract path name. 1691 * 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 1699 * will succeed. 1700 * 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}. 1705 * 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 1711 * 1712 * @since 1.6 1713 */ 1714 public long getFreeSpace() { 1715 SecurityManager sm = System.getSecurityManager(); 1716 if (sm != null) { 1717 sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); 1718 sm.checkRead(path); 1719 } 1720 return fs.getSpace(this, FileSystem.SPACE_FREE); 1721 } 1722 1723 /** 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 1729 * #getFreeSpace}. 1730 * 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. 1738 * 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}. 1743 * 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 1749 * 1750 * @since 1.6 1751 */ 1752 public long getUsableSpace() { 1753 SecurityManager sm = System.getSecurityManager(); 1754 if (sm != null) { 1755 sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); 1756 sm.checkRead(path); 1757 } 1758 return fs.getSpace(this, FileSystem.SPACE_USABLE); 1759 } 1760 1761 /* -- Temporary files -- */ 1762 1763 private static class TempDirectory { 1764 private TempDirectory() { } 1765 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() { 1770 return tmpdir; 1771 } 1772 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 1779 } else { 1780 n = Math.abs(n); 1781 } 1782 return new File(dir, prefix + Long.toString(n) + suffix); 1783 } 1784 } 1785 1786 /** 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: 1790 * 1791 * <ol> 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 1796 * machine. 1797 * </ol> 1798 * 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. 1802 * 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. 1808 * 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. 1818 * 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. 1828 * 1829 * @param prefix The prefix string to be used in generating the file's 1830 * name; must be at least three characters long 1831 * 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 1835 * 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 1839 * 1840 * @return An abstract pathname denoting a newly-created empty file 1841 * 1842 * @throws IllegalArgumentException 1843 * If the <code>prefix</code> argument contains fewer than three 1844 * characters 1845 * 1846 * @throws IOException If a file could not be created 1847 * 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 1852 * 1853 * @since 1.2 1854 */ 1855 public static File createTempFile(String prefix, String suffix, 1856 File directory) 1857 throws IOException 1858 { 1859 if (prefix.length() < 3) 1860 throw new IllegalArgumentException("Prefix string too short"); 1861 if (suffix == null) 1862 suffix = ".tmp"; 1863 1864 File tmpdir = (directory != null) ? directory : TempDirectory.location(); 1865 SecurityManager sm = System.getSecurityManager(); 1866 File f; 1867 do { 1868 f = TempDirectory.generateFile(prefix, suffix, tmpdir); 1869 if (sm != null) { 1870 try { 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"); 1876 throw se; 1877 } 1878 } 1879 } while (!fs.createFileExclusively(f.getPath())); 1880 return f; 1881 } 1882 1883 /** 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>. 1889 * 1890 * <p> The {@link 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. 1896 * 1897 * @param prefix The prefix string to be used in generating the file's 1898 * name; must be at least three characters long 1899 * 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 1903 * 1904 * @return An abstract pathname denoting a newly-created empty file 1905 * 1906 * @throws IllegalArgumentException 1907 * If the <code>prefix</code> argument contains fewer than three 1908 * characters 1909 * 1910 * @throws IOException If a file could not be created 1911 * 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 1916 * 1917 * @since 1.2 1918 * @see java.nio.file.Files#createTempDirectory(String,FileAttribute[]) 1919 */ 1920 public static File createTempFile(String prefix, String suffix) 1921 throws IOException 1922 { 1923 return createTempFile(prefix, suffix, null); 1924 } 1925 1926 /* -- Basic infrastructure -- */ 1927 1928 /** 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. 1933 * 1934 * @param pathname The abstract pathname to be compared to this abstract 1935 * pathname 1936 * 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 1942 * 1943 * @since 1.2 1944 */ 1945 public int compareTo(File pathname) { 1946 return fs.compare(this, pathname); 1947 } 1948 1949 /** 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. 1957 * 1958 * @param obj The object to be compared with this abstract pathname 1959 * 1960 * @return <code>true</code> if and only if the objects are the same; 1961 * <code>false</code> otherwise 1962 */ 1963 public boolean equals(Object obj) { 1964 if ((obj != null) && (obj instanceof File)) { 1965 return compareTo((File)obj) == 0; 1966 } 1967 return false; 1968 } 1969 1970 /** 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. 1981 * 1982 * @return A hash code for this abstract pathname 1983 */ 1984 public int hashCode() { 1985 return fs.hashCode(this); 1986 } 1987 1988 /** 1989 * Returns the pathname string of this abstract pathname. This is just the 1990 * string returned by the <code>{@link #getPath}</code> method. 1991 * 1992 * @return The string form of this abstract pathname 1993 */ 1994 public String toString() { 1995 return getPath(); 1996 } 1997 1998 /** 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. 2002 * <p> 2003 * @serialData Default fields followed by separator character. 2004 */ 2005 private synchronized void writeObject(java.io.ObjectOutputStream s) 2006 throws IOException 2007 { 2008 s.defaultWriteObject(); 2009 s.writeChar(separatorChar); // Add the separator character 2010 } 2011 2012 /** 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. 2017 */ 2018 private synchronized void readObject(java.io.ObjectInputStream s) 2019 throws IOException, ClassNotFoundException 2020 { 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); 2028 } 2029 2030 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 2031 private static final long serialVersionUID = 301077366599181567L; 2032 2033 // -- Integration with java.nio.file -- 2034 2035 private volatile transient Path filePath; 2036 2037 /** 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}. 2041 * 2042 * <p> The first invocation of this method works as if invoking it were 2043 * equivalent to evaluating the expression: 2044 * <blockquote><pre> 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}. 2049 * 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 2052 * user directory. 2053 * 2054 * @return a {@code Path} constructed from this abstract path 2055 * 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}) 2059 * 2060 * @since 1.7 2061 * @see Path#toFile 2062 */ 2063 public Path toPath() { 2064 Path result = filePath; 2065 if (result == null) { 2066 synchronized (this) { 2067 result = filePath; 2068 if (result == null) { 2069 result = FileSystems.getDefault().getPath(path); 2070 filePath = result; 2071 } 2072 } 2073 } 2074 return result; 2075 } 2076 }