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