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