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