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