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