001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.io; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkNotNull; 019import static com.google.common.io.FileWriteMode.APPEND; 020 021import com.google.common.annotations.Beta; 022import com.google.common.annotations.GwtIncompatible; 023import com.google.common.annotations.J2ktIncompatible; 024import com.google.common.base.Joiner; 025import com.google.common.base.Optional; 026import com.google.common.base.Predicate; 027import com.google.common.base.Splitter; 028import com.google.common.collect.ImmutableList; 029import com.google.common.collect.ImmutableSet; 030import com.google.common.collect.Lists; 031import com.google.common.graph.SuccessorsFunction; 032import com.google.common.graph.Traverser; 033import com.google.common.hash.HashCode; 034import com.google.common.hash.HashFunction; 035import com.google.errorprone.annotations.CanIgnoreReturnValue; 036import com.google.errorprone.annotations.InlineMe; 037import com.google.j2objc.annotations.J2ObjCIncompatible; 038import java.io.BufferedReader; 039import java.io.BufferedWriter; 040import java.io.File; 041import java.io.FileInputStream; 042import java.io.FileNotFoundException; 043import java.io.FileOutputStream; 044import java.io.IOException; 045import java.io.InputStreamReader; 046import java.io.OutputStream; 047import java.io.OutputStreamWriter; 048import java.io.RandomAccessFile; 049import java.nio.MappedByteBuffer; 050import java.nio.channels.FileChannel; 051import java.nio.channels.FileChannel.MapMode; 052import java.nio.charset.Charset; 053import java.nio.charset.StandardCharsets; 054import java.util.ArrayList; 055import java.util.Arrays; 056import java.util.Collections; 057import java.util.List; 058import javax.annotation.CheckForNull; 059import org.checkerframework.checker.nullness.qual.Nullable; 060 061/** 062 * Provides utility methods for working with {@linkplain File files}. 063 * 064 * <p>{@link java.nio.file.Path} users will find similar utilities in {@link MoreFiles} and the 065 * JDK's {@link java.nio.file.Files} class. 066 * 067 * @author Chris Nokleberg 068 * @author Colin Decker 069 * @since 1.0 070 */ 071@J2ktIncompatible 072@GwtIncompatible 073@ElementTypesAreNonnullByDefault 074public final class Files { 075 076 private Files() {} 077 078 /** 079 * Returns a buffered reader that reads from a file using the given character set. 080 * 081 * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link 082 * java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}. 083 * 084 * @param file the file to read from 085 * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for 086 * helpful predefined constants 087 * @return the buffered reader 088 */ 089 public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException { 090 checkNotNull(file); 091 checkNotNull(charset); 092 return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); 093 } 094 095 /** 096 * Returns a buffered writer that writes to a file using the given character set. 097 * 098 * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link 099 * java.nio.file.Files#newBufferedWriter(java.nio.file.Path, Charset, 100 * java.nio.file.OpenOption...)}. 101 * 102 * @param file the file to write to 103 * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for 104 * helpful predefined constants 105 * @return the buffered writer 106 */ 107 public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException { 108 checkNotNull(file); 109 checkNotNull(charset); 110 return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)); 111 } 112 113 /** 114 * Returns a new {@link ByteSource} for reading bytes from the given file. 115 * 116 * @since 14.0 117 */ 118 public static ByteSource asByteSource(File file) { 119 return new FileByteSource(file); 120 } 121 122 private static final class FileByteSource extends 123 ByteSource 124 { 125 126 private final File file; 127 128 private FileByteSource(File file) { 129 this.file = checkNotNull(file); 130 } 131 132 @Override 133 public FileInputStream openStream() throws IOException { 134 return new FileInputStream(file); 135 } 136 137 @Override 138 public Optional<Long> sizeIfKnown() { 139 if (file.isFile()) { 140 return Optional.of(file.length()); 141 } else { 142 return Optional.absent(); 143 } 144 } 145 146 @Override 147 public long size() throws IOException { 148 if (!file.isFile()) { 149 throw new FileNotFoundException(file.toString()); 150 } 151 return file.length(); 152 } 153 154 @Override 155 public byte[] read() throws IOException { 156 Closer closer = Closer.create(); 157 try { 158 FileInputStream in = closer.register(openStream()); 159 return ByteStreams.toByteArray(in, in.getChannel().size()); 160 } catch (Throwable e) { 161 throw closer.rethrow(e); 162 } finally { 163 closer.close(); 164 } 165 } 166 167 @Override 168 public String toString() { 169 return "Files.asByteSource(" + file + ")"; 170 } 171 } 172 173 /** 174 * Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes} 175 * control how the file is opened for writing. When no mode is provided, the file will be 176 * truncated before writing. When the {@link FileWriteMode#APPEND APPEND} mode is provided, writes 177 * will append to the end of the file without truncating it. 178 * 179 * @since 14.0 180 */ 181 public static ByteSink asByteSink(File file, FileWriteMode... modes) { 182 return new FileByteSink(file, modes); 183 } 184 185 private static final class FileByteSink extends ByteSink { 186 187 private final File file; 188 private final ImmutableSet<FileWriteMode> modes; 189 190 private FileByteSink(File file, FileWriteMode... modes) { 191 this.file = checkNotNull(file); 192 this.modes = ImmutableSet.copyOf(modes); 193 } 194 195 @Override 196 public FileOutputStream openStream() throws IOException { 197 return new FileOutputStream(file, modes.contains(APPEND)); 198 } 199 200 @Override 201 public String toString() { 202 return "Files.asByteSink(" + file + ", " + modes + ")"; 203 } 204 } 205 206 /** 207 * Returns a new {@link CharSource} for reading character data from the given file using the given 208 * character set. 209 * 210 * @since 14.0 211 */ 212 public static CharSource asCharSource(File file, Charset charset) { 213 return asByteSource(file).asCharSource(charset); 214 } 215 216 /** 217 * Returns a new {@link CharSink} for writing character data to the given file using the given 218 * character set. The given {@code modes} control how the file is opened for writing. When no mode 219 * is provided, the file will be truncated before writing. When the {@link FileWriteMode#APPEND 220 * APPEND} mode is provided, writes will append to the end of the file without truncating it. 221 * 222 * @since 14.0 223 */ 224 public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) { 225 return asByteSink(file, modes).asCharSink(charset); 226 } 227 228 /** 229 * Reads all bytes from a file into a byte array. 230 * 231 * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#readAllBytes}. 232 * 233 * @param file the file to read from 234 * @return a byte array containing all the bytes from file 235 * @throws IllegalArgumentException if the file is bigger than the largest possible byte array 236 * (2^31 - 1) 237 * @throws IOException if an I/O error occurs 238 */ 239 public static byte[] toByteArray(File file) throws IOException { 240 return asByteSource(file).read(); 241 } 242 243 /** 244 * Reads all characters from a file into a {@link String}, using the given character set. 245 * 246 * @param file the file to read from 247 * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for 248 * helpful predefined constants 249 * @return a string containing all the characters from the file 250 * @throws IOException if an I/O error occurs 251 * @deprecated Prefer {@code asCharSource(file, charset).read()}. 252 */ 253 @Deprecated 254 @InlineMe( 255 replacement = "Files.asCharSource(file, charset).read()", 256 imports = "com.google.common.io.Files") 257 public static String toString(File file, Charset charset) throws IOException { 258 return asCharSource(file, charset).read(); 259 } 260 261 /** 262 * Overwrites a file with the contents of a byte array. 263 * 264 * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link 265 * java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}. 266 * 267 * @param from the bytes to write 268 * @param to the destination file 269 * @throws IOException if an I/O error occurs 270 */ 271 public static void write(byte[] from, File to) throws IOException { 272 asByteSink(to).write(from); 273 } 274 275 /** 276 * Writes a character sequence (such as a string) to a file using the given character set. 277 * 278 * @param from the character sequence to write 279 * @param to the destination file 280 * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for 281 * helpful predefined constants 282 * @throws IOException if an I/O error occurs 283 * @deprecated Prefer {@code asCharSink(to, charset).write(from)}. 284 */ 285 @Deprecated 286 @InlineMe( 287 replacement = "Files.asCharSink(to, charset).write(from)", 288 imports = "com.google.common.io.Files") 289 public static void write(CharSequence from, File to, Charset charset) throws IOException { 290 asCharSink(to, charset).write(from); 291 } 292 293 /** 294 * Copies all bytes from a file to an output stream. 295 * 296 * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link 297 * java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}. 298 * 299 * @param from the source file 300 * @param to the output stream 301 * @throws IOException if an I/O error occurs 302 */ 303 public static void copy(File from, OutputStream to) throws IOException { 304 asByteSource(from).copyTo(to); 305 } 306 307 /** 308 * Copies all the bytes from one file to another. 309 * 310 * <p>Copying is not an atomic operation - in the case of an I/O error, power loss, process 311 * termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you 312 * need to guard against those conditions, you should employ other file-level synchronization. 313 * 314 * <p><b>Warning:</b> If {@code to} represents an existing file, that file will be overwritten 315 * with the contents of {@code from}. If {@code to} and {@code from} refer to the <i>same</i> 316 * file, the contents of that file will be deleted. 317 * 318 * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link 319 * java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}. 320 * 321 * @param from the source file 322 * @param to the destination file 323 * @throws IOException if an I/O error occurs 324 * @throws IllegalArgumentException if {@code from.equals(to)} 325 */ 326 public static void copy(File from, File to) throws IOException { 327 checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to); 328 asByteSource(from).copyTo(asByteSink(to)); 329 } 330 331 /** 332 * Copies all characters from a file to an appendable object, using the given character set. 333 * 334 * @param from the source file 335 * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for 336 * helpful predefined constants 337 * @param to the appendable object 338 * @throws IOException if an I/O error occurs 339 * @deprecated Prefer {@code asCharSource(from, charset).copyTo(to)}. 340 */ 341 @Deprecated 342 @InlineMe( 343 replacement = "Files.asCharSource(from, charset).copyTo(to)", 344 imports = "com.google.common.io.Files") 345 public 346 static void copy(File from, Charset charset, Appendable to) throws IOException { 347 asCharSource(from, charset).copyTo(to); 348 } 349 350 /** 351 * Appends a character sequence (such as a string) to a file using the given character set. 352 * 353 * @param from the character sequence to append 354 * @param to the destination file 355 * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for 356 * helpful predefined constants 357 * @throws IOException if an I/O error occurs 358 * @deprecated Prefer {@code asCharSink(to, charset, FileWriteMode.APPEND).write(from)}. This 359 * method is scheduled to be removed in October 2019. 360 */ 361 @Deprecated 362 @InlineMe( 363 replacement = "Files.asCharSink(to, charset, FileWriteMode.APPEND).write(from)", 364 imports = {"com.google.common.io.FileWriteMode", "com.google.common.io.Files"}) 365 public 366 static void append(CharSequence from, File to, Charset charset) throws IOException { 367 asCharSink(to, charset, FileWriteMode.APPEND).write(from); 368 } 369 370 /** 371 * Returns true if the given files exist, are not directories, and contain the same bytes. 372 * 373 * @throws IOException if an I/O error occurs 374 */ 375 public static boolean equal(File file1, File file2) throws IOException { 376 checkNotNull(file1); 377 checkNotNull(file2); 378 if (file1 == file2 || file1.equals(file2)) { 379 return true; 380 } 381 382 /* 383 * Some operating systems may return zero as the length for files denoting system-dependent 384 * entities such as devices or pipes, in which case we must fall back on comparing the bytes 385 * directly. 386 */ 387 long len1 = file1.length(); 388 long len2 = file2.length(); 389 if (len1 != 0 && len2 != 0 && len1 != len2) { 390 return false; 391 } 392 return asByteSource(file1).contentEquals(asByteSource(file2)); 393 } 394 395 /** 396 * Atomically creates a new directory somewhere beneath the system's temporary directory (as 397 * defined by the {@code java.io.tmpdir} system property), and returns its name. 398 * 399 * <p>The temporary directory is created with permissions restricted to the current user or, in 400 * the case of Android, the current app. If that is not possible (as is the case under the very 401 * old Android Ice Cream Sandwich release), then this method throws an exception instead of 402 * creating a directory that would be more accessible. (This behavior is new in Guava 32.0.0. 403 * Previous versions would create a directory that is more accessible, as discussed in <a 404 * href="https://github.com/google/guava/issues/4011">CVE-2020-8908</a>.) 405 * 406 * <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to 407 * create a directory, not a regular file. A common pitfall is to call {@code createTempFile}, 408 * delete the file and create a directory in its place, but this leads a race condition which can 409 * be exploited to create security vulnerabilities, especially when executable files are to be 410 * written into the directory. 411 * 412 * <p>This method assumes that the temporary volume is writable, has free inodes and free blocks, 413 * and that it will not be called thousands of times per second. 414 * 415 * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link 416 * java.nio.file.Files#createTempDirectory}. 417 * 418 * @return the newly-created directory 419 * @throws IllegalStateException if the directory could not be created 420 * @throws UnsupportedOperationException if the system does not support creating temporary 421 * directories securely 422 * @deprecated For Android users, see the <a 423 * href="https://developer.android.com/training/data-storage" target="_blank">Data and File 424 * Storage overview</a> to select an appropriate temporary directory (perhaps {@code 425 * context.getCacheDir()}), and create your own directory under that. (For example, you might 426 * use {@code new File(context.getCacheDir(), "directoryname").mkdir()}, or, if you need an 427 * arbitrary number of temporary directories, you might have to generate multiple directory 428 * names in a loop until {@code mkdir()} returns {@code true}.) For developers on Java 7 or 429 * later, use {@link java.nio.file.Files#createTempDirectory}, transforming it to a {@link 430 * File} using {@link java.nio.file.Path#toFile() toFile()} if needed. To restrict permissions 431 * as this method does, pass {@code 432 * PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))} to your 433 * call to {@code createTempDirectory}. 434 */ 435 @Beta 436 @Deprecated 437 @J2ObjCIncompatible 438 public static File createTempDir() { 439 return TempFileCreator.INSTANCE.createTempDir(); 440 } 441 442 /** 443 * Creates an empty file or updates the last updated timestamp on the same as the unix command of 444 * the same name. 445 * 446 * @param file the file to create or update 447 * @throws IOException if an I/O error occurs 448 */ 449 @SuppressWarnings("GoodTime") // reading system time without TimeSource 450 public static void touch(File file) throws IOException { 451 checkNotNull(file); 452 if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) { 453 throw new IOException("Unable to update modification time of " + file); 454 } 455 } 456 457 /** 458 * Creates any necessary but nonexistent parent directories of the specified file. Note that if 459 * this operation fails it may have succeeded in creating some (but not all) of the necessary 460 * parent directories. 461 * 462 * @throws IOException if an I/O error occurs, or if any necessary but nonexistent parent 463 * directories of the specified file could not be created. 464 * @since 4.0 465 */ 466 public static void createParentDirs(File file) throws IOException { 467 checkNotNull(file); 468 File parent = file.getCanonicalFile().getParentFile(); 469 if (parent == null) { 470 /* 471 * The given directory is a filesystem root. All zero of its ancestors exist. This doesn't 472 * mean that the root itself exists -- consider x:\ on a Windows machine without such a drive 473 * -- or even that the caller can create it, but this method makes no such guarantees even for 474 * non-root files. 475 */ 476 return; 477 } 478 parent.mkdirs(); 479 if (!parent.isDirectory()) { 480 throw new IOException("Unable to create parent directories of " + file); 481 } 482 } 483 484 /** 485 * Moves a file from one path to another. This method can rename a file and/or move it to a 486 * different directory. In either case {@code to} must be the target path for the file itself; not 487 * just the new name for the file or the path to the new parent directory. 488 * 489 * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#move}. 490 * 491 * @param from the source file 492 * @param to the destination file 493 * @throws IOException if an I/O error occurs 494 * @throws IllegalArgumentException if {@code from.equals(to)} 495 */ 496 public static void move(File from, File to) throws IOException { 497 checkNotNull(from); 498 checkNotNull(to); 499 checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to); 500 501 if (!from.renameTo(to)) { 502 copy(from, to); 503 if (!from.delete()) { 504 if (!to.delete()) { 505 throw new IOException("Unable to delete " + to); 506 } 507 throw new IOException("Unable to delete " + from); 508 } 509 } 510 } 511 512 /** 513 * Reads the first line from a file. The line does not include line-termination characters, but 514 * does include other leading and trailing whitespace. 515 * 516 * @param file the file to read from 517 * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for 518 * helpful predefined constants 519 * @return the first line, or null if the file is empty 520 * @throws IOException if an I/O error occurs 521 * @deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}. 522 */ 523 @Deprecated 524 @InlineMe( 525 replacement = "Files.asCharSource(file, charset).readFirstLine()", 526 imports = "com.google.common.io.Files") 527 @CheckForNull 528 public 529 static String readFirstLine(File file, Charset charset) throws IOException { 530 return asCharSource(file, charset).readFirstLine(); 531 } 532 533 /** 534 * Reads all of the lines from a file. The lines do not include line-termination characters, but 535 * do include other leading and trailing whitespace. 536 * 537 * <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code 538 * Files.asCharSource(file, charset).readLines()}. 539 * 540 * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link 541 * java.nio.file.Files#readAllLines(java.nio.file.Path, Charset)}. 542 * 543 * @param file the file to read from 544 * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for 545 * helpful predefined constants 546 * @return a mutable {@link List} containing all the lines 547 * @throws IOException if an I/O error occurs 548 */ 549 public static List<String> readLines(File file, Charset charset) throws IOException { 550 // don't use asCharSource(file, charset).readLines() because that returns 551 // an immutable list, which would change the behavior of this method 552 return asCharSource(file, charset) 553 .readLines( 554 new LineProcessor<List<String>>() { 555 final List<String> result = Lists.newArrayList(); 556 557 @Override 558 public boolean processLine(String line) { 559 result.add(line); 560 return true; 561 } 562 563 @Override 564 public List<String> getResult() { 565 return result; 566 } 567 }); 568 } 569 570 /** 571 * Streams lines from a {@link File}, stopping when our callback returns false, or we have read 572 * all of the lines. 573 * 574 * @param file the file to read from 575 * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for 576 * helpful predefined constants 577 * @param callback the {@link LineProcessor} to use to handle the lines 578 * @return the output of processing the lines 579 * @throws IOException if an I/O error occurs 580 * @deprecated Prefer {@code asCharSource(file, charset).readLines(callback)}. 581 */ 582 @Deprecated 583 @InlineMe( 584 replacement = "Files.asCharSource(file, charset).readLines(callback)", 585 imports = "com.google.common.io.Files") 586 @CanIgnoreReturnValue // some processors won't return a useful result 587 @ParametricNullness 588 public 589 static <T extends @Nullable Object> T readLines( 590 File file, Charset charset, LineProcessor<T> callback) throws IOException { 591 return asCharSource(file, charset).readLines(callback); 592 } 593 594 /** 595 * Process the bytes of a file. 596 * 597 * <p>(If this seems too complicated, maybe you're looking for {@link #toByteArray}.) 598 * 599 * @param file the file to read 600 * @param processor the object to which the bytes of the file are passed. 601 * @return the result of the byte processor 602 * @throws IOException if an I/O error occurs 603 * @deprecated Prefer {@code asByteSource(file).read(processor)}. 604 */ 605 @Deprecated 606 @InlineMe( 607 replacement = "Files.asByteSource(file).read(processor)", 608 imports = "com.google.common.io.Files") 609 @CanIgnoreReturnValue // some processors won't return a useful result 610 @ParametricNullness 611 public 612 static <T extends @Nullable Object> T readBytes(File file, ByteProcessor<T> processor) 613 throws IOException { 614 return asByteSource(file).read(processor); 615 } 616 617 /** 618 * Computes the hash code of the {@code file} using {@code hashFunction}. 619 * 620 * @param file the file to read 621 * @param hashFunction the hash function to use to hash the data 622 * @return the {@link HashCode} of all of the bytes in the file 623 * @throws IOException if an I/O error occurs 624 * @since 12.0 625 * @deprecated Prefer {@code asByteSource(file).hash(hashFunction)}. 626 */ 627 @Deprecated 628 @InlineMe( 629 replacement = "Files.asByteSource(file).hash(hashFunction)", 630 imports = "com.google.common.io.Files") 631 public 632 static HashCode hash(File file, HashFunction hashFunction) throws IOException { 633 return asByteSource(file).hash(hashFunction); 634 } 635 636 /** 637 * Fully maps a file read-only in to memory as per {@link 638 * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}. 639 * 640 * <p>Files are mapped from offset 0 to its length. 641 * 642 * <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes. 643 * 644 * @param file the file to map 645 * @return a read-only buffer reflecting {@code file} 646 * @throws FileNotFoundException if the {@code file} does not exist 647 * @throws IOException if an I/O error occurs 648 * @see FileChannel#map(MapMode, long, long) 649 * @since 2.0 650 */ 651 public static MappedByteBuffer map(File file) throws IOException { 652 checkNotNull(file); 653 return map(file, MapMode.READ_ONLY); 654 } 655 656 /** 657 * Fully maps a file in to memory as per {@link 658 * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link 659 * MapMode}. 660 * 661 * <p>Files are mapped from offset 0 to its length. 662 * 663 * <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes. 664 * 665 * @param file the file to map 666 * @param mode the mode to use when mapping {@code file} 667 * @return a buffer reflecting {@code file} 668 * @throws FileNotFoundException if the {@code file} does not exist 669 * @throws IOException if an I/O error occurs 670 * @see FileChannel#map(MapMode, long, long) 671 * @since 2.0 672 */ 673 public static MappedByteBuffer map(File file, MapMode mode) throws IOException { 674 return mapInternal(file, mode, -1); 675 } 676 677 /** 678 * Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, 679 * long, long)} using the requested {@link MapMode}. 680 * 681 * <p>Files are mapped from offset 0 to {@code size}. 682 * 683 * <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created 684 * with the requested {@code size}. Thus this method is useful for creating memory mapped files 685 * which do not yet exist. 686 * 687 * <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes. 688 * 689 * @param file the file to map 690 * @param mode the mode to use when mapping {@code file} 691 * @return a buffer reflecting {@code file} 692 * @throws IOException if an I/O error occurs 693 * @see FileChannel#map(MapMode, long, long) 694 * @since 2.0 695 */ 696 public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException { 697 checkArgument(size >= 0, "size (%s) may not be negative", size); 698 return mapInternal(file, mode, size); 699 } 700 701 private static MappedByteBuffer mapInternal(File file, MapMode mode, long size) 702 throws IOException { 703 checkNotNull(file); 704 checkNotNull(mode); 705 706 Closer closer = Closer.create(); 707 try { 708 RandomAccessFile raf = 709 closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw")); 710 FileChannel channel = closer.register(raf.getChannel()); 711 return channel.map(mode, 0, size == -1 ? channel.size() : size); 712 } catch (Throwable e) { 713 throw closer.rethrow(e); 714 } finally { 715 closer.close(); 716 } 717 } 718 719 /** 720 * Returns the lexically cleaned form of the path name, <i>usually</i> (but not always) equivalent 721 * to the original. The following heuristics are used: 722 * 723 * <ul> 724 * <li>empty string becomes . 725 * <li>. stays as . 726 * <li>fold out ./ 727 * <li>fold out ../ when possible 728 * <li>collapse multiple slashes 729 * <li>delete trailing slashes (unless the path is just "/") 730 * </ul> 731 * 732 * <p>These heuristics do not always match the behavior of the filesystem. In particular, consider 733 * the path {@code a/../b}, which {@code simplifyPath} will change to {@code b}. If {@code a} is a 734 * symlink to {@code x}, {@code a/../b} may refer to a sibling of {@code x}, rather than the 735 * sibling of {@code a} referred to by {@code b}. 736 * 737 * @since 11.0 738 */ 739 public static String simplifyPath(String pathname) { 740 checkNotNull(pathname); 741 if (pathname.length() == 0) { 742 return "."; 743 } 744 745 // split the path apart 746 Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname); 747 List<String> path = new ArrayList<>(); 748 749 // resolve ., .., and // 750 for (String component : components) { 751 switch (component) { 752 case ".": 753 continue; 754 case "..": 755 if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) { 756 path.remove(path.size() - 1); 757 } else { 758 path.add(".."); 759 } 760 break; 761 default: 762 path.add(component); 763 break; 764 } 765 } 766 767 // put it back together 768 String result = Joiner.on('/').join(path); 769 if (pathname.charAt(0) == '/') { 770 result = "/" + result; 771 } 772 773 while (result.startsWith("/../")) { 774 result = result.substring(3); 775 } 776 if (result.equals("/..")) { 777 result = "/"; 778 } else if ("".equals(result)) { 779 result = "."; 780 } 781 782 return result; 783 } 784 785 /** 786 * Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> for 787 * the given file name, or the empty string if the file has no extension. The result does not 788 * include the '{@code .}'. 789 * 790 * <p><b>Note:</b> This method simply returns everything after the last '{@code .}' in the file's 791 * name as determined by {@link File#getName}. It does not account for any filesystem-specific 792 * behavior that the {@link File} API does not already account for. For example, on NTFS it will 793 * report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS 794 * will drop the {@code ":.txt"} part of the name when the file is actually created on the 795 * filesystem due to NTFS's <a href="https://goo.gl/vTpJi4">Alternate Data Streams</a>. 796 * 797 * @since 11.0 798 */ 799 public static String getFileExtension(String fullName) { 800 checkNotNull(fullName); 801 String fileName = new File(fullName).getName(); 802 int dotIndex = fileName.lastIndexOf('.'); 803 return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1); 804 } 805 806 /** 807 * Returns the file name without its <a 808 * href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is 809 * similar to the {@code basename} unix command. The result does not include the '{@code .}'. 810 * 811 * @param file The name of the file to trim the extension from. This can be either a fully 812 * qualified file name (including a path) or just a file name. 813 * @return The file name without its path or extension. 814 * @since 14.0 815 */ 816 public static String getNameWithoutExtension(String file) { 817 checkNotNull(file); 818 String fileName = new File(file).getName(); 819 int dotIndex = fileName.lastIndexOf('.'); 820 return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex); 821 } 822 823 /** 824 * Returns a {@link Traverser} instance for the file and directory tree. The returned traverser 825 * starts from a {@link File} and will return all files and directories it encounters. 826 * 827 * <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no 828 * way to ensure that a symbolic link to a directory is not followed when traversing the tree. In 829 * this case, iterables created by this traverser could contain files that are outside of the 830 * given directory or even be infinite if there is a symbolic link loop. 831 * 832 * <p>If available, consider using {@link MoreFiles#fileTraverser()} instead. It behaves the same 833 * except that it doesn't follow symbolic links and returns {@code Path} instances. 834 * 835 * <p>If the {@link File} passed to one of the {@link Traverser} methods does not exist or is not 836 * a directory, no exception will be thrown and the returned {@link Iterable} will contain a 837 * single element: that file. 838 * 839 * <p>Example: {@code Files.fileTraverser().depthFirstPreOrder(new File("/"))} may return files 840 * with the following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home", 841 * "/home/alice", ...]} 842 * 843 * @since 23.5 844 */ 845 public static Traverser<File> fileTraverser() { 846 return Traverser.forTree(FILE_TREE); 847 } 848 849 private static final SuccessorsFunction<File> FILE_TREE = 850 new SuccessorsFunction<File>() { 851 @Override 852 public Iterable<File> successors(File file) { 853 // check isDirectory() just because it may be faster than listFiles() on a non-directory 854 if (file.isDirectory()) { 855 File[] files = file.listFiles(); 856 if (files != null) { 857 return Collections.unmodifiableList(Arrays.asList(files)); 858 } 859 } 860 861 return ImmutableList.of(); 862 } 863 }; 864 865 /** 866 * Returns a predicate that returns the result of {@link File#isDirectory} on input files. 867 * 868 * @since 15.0 869 */ 870 public static Predicate<File> isDirectory() { 871 return FilePredicate.IS_DIRECTORY; 872 } 873 874 /** 875 * Returns a predicate that returns the result of {@link File#isFile} on input files. 876 * 877 * @since 15.0 878 */ 879 public static Predicate<File> isFile() { 880 return FilePredicate.IS_FILE; 881 } 882 883 private enum FilePredicate implements Predicate<File> { 884 IS_DIRECTORY { 885 @Override 886 public boolean apply(File file) { 887 return file.isDirectory(); 888 } 889 890 @Override 891 public String toString() { 892 return "Files.isDirectory()"; 893 } 894 }, 895 896 IS_FILE { 897 @Override 898 public boolean apply(File file) { 899 return file.isFile(); 900 } 901 902 @Override 903 public String toString() { 904 return "Files.isFile()"; 905 } 906 } 907 } 908}