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