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