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