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