Class Files


  • @GwtIncompatible
    public final class Files
    extends Object
    Provides utility methods for working with files.

    Path users will find similar utilities in MoreFiles and the JDK's Files class.

    Since:
    1.0
    Author:
    Chris Nokleberg, Colin Decker
    • Method Detail

      • asByteSink

        public static ByteSink asByteSink​(File file,
                                          FileWriteMode... modes)
        Returns a new ByteSink for writing bytes to the given file. The given modes control how the file is opened for writing. When no mode is provided, the file will be truncated before writing. When the APPEND mode is provided, writes will append to the end of the file without truncating it.
        Since:
        14.0
      • asCharSink

        public static CharSink asCharSink​(File file,
                                          Charset charset,
                                          FileWriteMode... modes)
        Returns a new CharSink for writing character data to the given file using the given character set. The given modes control how the file is opened for writing. When no mode is provided, the file will be truncated before writing. When the APPEND mode is provided, writes will append to the end of the file without truncating it.
        Since:
        14.0
      • toString

        @Beta
        @Deprecated
        public static String toString​(File file,
                                      Charset charset)
                               throws IOException
        Deprecated.
        Prefer asCharSource(file, charset).read(). This method is scheduled to be removed in October 2019.
        Reads all characters from a file into a String, using the given character set.
        Parameters:
        file - the file to read from
        charset - the charset used to decode the input stream; see StandardCharsets for helpful predefined constants
        Returns:
        a string containing all the characters from the file
        Throws:
        IOException - if an I/O error occurs
      • write

        @Beta
        @Deprecated
        public static void write​(CharSequence from,
                                 File to,
                                 Charset charset)
                          throws IOException
        Deprecated.
        Prefer asCharSink(to, charset).write(from). This method is scheduled to be removed in October 2019.
        Writes a character sequence (such as a string) to a file using the given character set.
        Parameters:
        from - the character sequence to write
        to - the destination file
        charset - the charset used to encode the output stream; see StandardCharsets for helpful predefined constants
        Throws:
        IOException - if an I/O error occurs
      • copy

        @Beta
        public static void copy​(File from,
                                File to)
                         throws IOException
        Copies all the bytes from one file to another.

        Copying is not an atomic operation - in the case of an I/O error, power loss, process termination, or other problems, to may not be a complete copy of from. If you need to guard against those conditions, you should employ other file-level synchronization.

        Warning: If to represents an existing file, that file will be overwritten with the contents of from. If to and from refer to the same file, the contents of that file will be deleted.

        Path equivalent: Files.copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...).

        Parameters:
        from - the source file
        to - the destination file
        Throws:
        IOException - if an I/O error occurs
        IllegalArgumentException - if from.equals(to)
      • copy

        @Beta
        @Deprecated
        public static void copy​(File from,
                                Charset charset,
                                Appendable to)
                         throws IOException
        Deprecated.
        Prefer asCharSource(from, charset).copyTo(to). This method is scheduled to be removed in October 2019.
        Copies all characters from a file to an appendable object, using the given character set.
        Parameters:
        from - the source file
        charset - the charset used to decode the input stream; see StandardCharsets for helpful predefined constants
        to - the appendable object
        Throws:
        IOException - if an I/O error occurs
      • append

        @Beta
        @Deprecated
        public static void append​(CharSequence from,
                                  File to,
                                  Charset charset)
                           throws IOException
        Deprecated.
        Prefer asCharSink(to, charset, FileWriteMode.APPEND).write(from). This method is scheduled to be removed in October 2019.
        Appends a character sequence (such as a string) to a file using the given character set.
        Parameters:
        from - the character sequence to append
        to - the destination file
        charset - the charset used to encode the output stream; see StandardCharsets for helpful predefined constants
        Throws:
        IOException - if an I/O error occurs
      • equal

        @Beta
        public static boolean equal​(File file1,
                                    File file2)
                             throws IOException
        Returns true if the given files exist, are not directories, and contain the same bytes.
        Throws:
        IOException - if an I/O error occurs
      • touch

        @Beta
        public static void touch​(File file)
                          throws IOException
        Creates an empty file or updates the last updated timestamp on the same as the unix command of the same name.
        Parameters:
        file - the file to create or update
        Throws:
        IOException - if an I/O error occurs
      • createParentDirs

        @Beta
        public static void createParentDirs​(File file)
                                     throws IOException
        Creates any necessary but nonexistent parent directories of the specified file. Note that if this operation fails it may have succeeded in creating some (but not all) of the necessary parent directories.
        Throws:
        IOException - if an I/O error occurs, or if any necessary but nonexistent parent directories of the specified file could not be created.
        Since:
        4.0
      • readFirstLine

        @Beta
        @Deprecated
        @CheckForNull
        public static String readFirstLine​(File file,
                                           Charset charset)
                                    throws IOException
        Deprecated.
        Prefer asCharSource(file, charset).readFirstLine(). This method is scheduled to be removed in October 2019.
        Reads the first line from a file. The line does not include line-termination characters, but does include other leading and trailing whitespace.
        Parameters:
        file - the file to read from
        charset - the charset used to decode the input stream; see StandardCharsets for helpful predefined constants
        Returns:
        the first line, or null if the file is empty
        Throws:
        IOException - if an I/O error occurs
      • readLines

        @Beta
        public static List<StringreadLines​(File file,
                                             Charset charset)
                                      throws IOException
        Reads all of the lines from a file. The lines do not include line-termination characters, but do include other leading and trailing whitespace.

        This method returns a mutable List. For an ImmutableList, use Files.asCharSource(file, charset).readLines().

        Path equivalent: Files.readAllLines(java.nio.file.Path, Charset).

        Parameters:
        file - the file to read from
        charset - the charset used to decode the input stream; see StandardCharsets for helpful predefined constants
        Returns:
        a mutable List containing all the lines
        Throws:
        IOException - if an I/O error occurs
      • readLines

        @Beta
        @Deprecated
        @CanIgnoreReturnValue
        public static <T extends @Nullable Object> T readLines​(File file,
                                                               Charset charset,
                                                               LineProcessor<T> callback)
                                                        throws IOException
        Deprecated.
        Prefer asCharSource(file, charset).readLines(callback). This method is scheduled to be removed in October 2019.
        Streams lines from a File, stopping when our callback returns false, or we have read all of the lines.
        Parameters:
        file - the file to read from
        charset - the charset used to decode the input stream; see StandardCharsets for helpful predefined constants
        callback - the LineProcessor to use to handle the lines
        Returns:
        the output of processing the lines
        Throws:
        IOException - if an I/O error occurs
      • hash

        @Beta
        @Deprecated
        public static HashCode hash​(File file,
                                    HashFunction hashFunction)
                             throws IOException
        Deprecated.
        Prefer asByteSource(file).hash(hashFunction). This method is scheduled to be removed in October 2019.
        Computes the hash code of the file using hashFunction.
        Parameters:
        file - the file to read
        hashFunction - the hash function to use to hash the data
        Returns:
        the HashCode of all of the bytes in the file
        Throws:
        IOException - if an I/O error occurs
        Since:
        12.0
      • simplifyPath

        @Beta
        public static String simplifyPath​(String pathname)
        Returns the lexically cleaned form of the path name, usually (but not always) equivalent to the original. The following heuristics are used:
        • empty string becomes .
        • . stays as .
        • fold out ./
        • fold out ../ when possible
        • collapse multiple slashes
        • delete trailing slashes (unless the path is just "/")

        These heuristics do not always match the behavior of the filesystem. In particular, consider the path a/../b, which simplifyPath will change to b. If a is a symlink to x, a/../b may refer to a sibling of x, rather than the sibling of a referred to by b.

        Since:
        11.0
      • getFileExtension

        @Beta
        public static String getFileExtension​(String fullName)
        Returns the file extension for the given file name, or the empty string if the file has no extension. The result does not include the '.'.

        Note: This method simply returns everything after the last '.' in the file's name as determined by File.getName(). It does not account for any filesystem-specific behavior that the File API does not already account for. For example, on NTFS it will report "txt" as the extension for the filename "foo.exe:.txt" even though NTFS will drop the ":.txt" part of the name when the file is actually created on the filesystem due to NTFS's Alternate Data Streams.

        Since:
        11.0
      • getNameWithoutExtension

        @Beta
        public static String getNameWithoutExtension​(String file)
        Returns the file name without its file extension or path. This is similar to the basename unix command. The result does not include the '.'.
        Parameters:
        file - The name of the file to trim the extension from. This can be either a fully qualified file name (including a path) or just a file name.
        Returns:
        The file name without its path or extension.
        Since:
        14.0
      • fileTraverser

        @Beta
        public static Traverser<FilefileTraverser()
        Returns a Traverser instance for the file and directory tree. The returned traverser starts from a File and will return all files and directories it encounters.

        Warning: File provides no support for symbolic links, and as such there is no way to ensure that a symbolic link to a directory is not followed when traversing the tree. In this case, iterables created by this traverser could contain files that are outside of the given directory or even be infinite if there is a symbolic link loop.

        If available, consider using MoreFiles#fileTraverser() instead. It behaves the same except that it doesn't follow symbolic links and returns Path instances.

        If the File passed to one of the Traverser methods does not exist or is not a directory, no exception will be thrown and the returned Iterable will contain a single element: that file.

        Example: Files.fileTraverser().depthFirstPreOrder(new File("/")) may return files with the following paths: ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home", "/home/alice", ...]

        Since:
        23.5