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