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