Class Files


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

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

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

      All Methods Static Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      static void  from,  to,  charset)
      Deprecated.
      Prefer asCharSink(to, charset, FileWriteMode.APPEND).write(from).
      static ByteSink  file, FileWriteMode... modes)
      Returns a new ByteSink for writing bytes to the given file.
      static ByteSource  file)
      Returns a new ByteSource for reading bytes from the given file.
      static CharSink  file,  charset, FileWriteMode... modes)
      Returns a new CharSink for writing character data to the given file using the given character set.
      static CharSource  file,  charset)
      Returns a new CharSource for reading character data from the given file using the given character set.
      static void  from,  to)
      Copies all the bytes from one file to another.
      static void  from,  to)
      Copies all bytes from a file to an output stream.
      static void  from,  charset,  to)
      Deprecated.
      Prefer asCharSource(from, charset).copyTo(to).
      static void  file)
      Creates any necessary but nonexistent parent directories of the specified file.
      static createTempDir()
      Deprecated.
      For Android users, see the to select an appropriate temporary directory (perhaps context.getCacheDir()).
      static boolean  file1,  file2)
      Returns true if the given files exist, are not directories, and contain the same bytes.
      static > fileTraverser()
      Returns a Traverser instance for the file and directory tree.
      static  fullName)
      Returns the for the given file name, or the empty string if the file has no extension.
      static  file)
      Returns the file name without its or path.
      static HashCode  file, HashFunction hashFunction)
      Deprecated.
      Prefer asByteSource(file).hash(hashFunction).
      static > isDirectory()
      Returns a predicate that returns the result of on input files.
      static > isFile()
      Returns a predicate that returns the result of on input files.
      static  file)
      Fully maps a file read-only in to memory as per .
      static  file,  mode)
      Fully maps a file in to memory as per using the requested .
      static  file,  mode, long size)
      Maps a file in to memory as per using the requested .
      static void  from,  to)
      Moves a file from one path to another.
      static  file,  charset)
      Returns a buffered reader that reads from a file using the given character set.
      static  file,  charset)
      Returns a buffered writer that writes to a file using the given character set.
      static <T> T  file, ByteProcessor<T> processor)
      Deprecated.
      Prefer asByteSource(file).read(processor).
      static  file,  charset)
      Deprecated.
      Prefer asCharSource(file, charset).readFirstLine().
      static <>  file,  charset)
      Reads all of the lines from a file.
      static <T> T  file,  charset, LineProcessor<T> callback)
      Deprecated.
      Prefer asCharSource(file, charset).readLines(callback).
      static  pathname)
      Returns the lexically cleaned form of the path name, usually (but not always) equivalent to the original.
      static byte[]  file)
      Reads all bytes from a file into a byte array.
      static  file,  charset)
      Deprecated.
      Prefer asCharSource(file, charset).read().
      static void  file)
      Creates an empty file or updates the last updated timestamp on the same as the unix command of the same name.
      static void write​(byte[] from,  to)
      Overwrites a file with the contents of a byte array.
      static void  from,  to,  charset)
      Deprecated.
      Prefer asCharSink(to, charset).write(from).
      • Methods inherited from class java.lang.

        , , , , , , , , , ,
    • Method Detail

      • newReader

        @Beta
        public static   file,
                                                charset)
                                        throws 
        Returns a buffered reader that reads from a file using the given character set.

        equivalent: .

        Parameters:
        file - the file to read from
        charset - the charset used to decode the input stream; see for helpful predefined constants
        Returns:
        the buffered reader
        Throws:
      • newWriter

        @Beta
        public static   file,
                                                charset)
                                        throws 
        Returns a buffered writer that writes to a file using the given character set.

        equivalent: .

        Parameters:
        file - the file to write to
        charset - the charset used to encode the output stream; see for helpful predefined constants
        Returns:
        the buffered writer
        Throws:
      • asByteSource

        public static  file)
        Returns a new ByteSource for reading bytes from the given file.
        Since:
        14.0
      • asByteSink

        public static  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
      • asCharSource

        public static  file,
                                               charset)
        Returns a new CharSource for reading character data from the given file using the given character set.
        Since:
        14.0
      • asCharSink

        public static  file,
                                           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
      • toByteArray

        @Beta
        public static byte[]  file)
                                  throws 
        Reads all bytes from a file into a byte array.

        equivalent: .

        Parameters:
        file - the file to read from
        Returns:
        a byte array containing all the bytes from file
        Throws:
        - if the file is bigger than the largest possible byte array (2^31 - 1)
        - if an I/O error occurs
      • toString

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

        @Beta
        public static void write​(byte[] from,
                                  to)
                          throws 
        Overwrites a file with the contents of a byte array.

        equivalent: .

        Parameters:
        from - the bytes to write
        to - the destination file
        Throws:
        - if an I/O error occurs
      • write

        @Beta
        
        public static void  from,
                                  to,
                                  charset)
                          throws 
        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 for helpful predefined constants
        Throws:
        - if an I/O error occurs
      • copy

        @Beta
        public static void  from,
                                 to)
                         throws 
        Copies all bytes from a file to an output stream.

        equivalent: .

        Parameters:
        from - the source file
        to - the output stream
        Throws:
        - if an I/O error occurs
      • copy

        @Beta
        public static void  from,
                                 to)
                         throws 
        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.

        equivalent: .

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

        @Beta
        
        public static void  from,
                                 charset,
                                 to)
                         throws 
        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 for helpful predefined constants
        to - the appendable object
        Throws:
        - if an I/O error occurs
      • append

        @Beta
        
        public static void  from,
                                   to,
                                   charset)
                           throws 
        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 for helpful predefined constants
        Throws:
        - if an I/O error occurs
      • equal

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

        @Beta
        
        public static  createTempDir()
        Deprecated.
        For Android users, see the to select an appropriate temporary directory (perhaps context.getCacheDir()). For developers on Java 7 or later, use , transforming it to a using if needed.
        Atomically creates a new directory somewhere beneath the system's temporary directory (as defined by the java.io.tmpdir system property), and returns its name.

        Use this method instead of when you wish to create a directory, not a regular file. A common pitfall is to call createTempFile, delete the file and create a directory in its place, but this leads a race condition which can be exploited to create security vulnerabilities, especially when executable files are to be written into the directory.

        Depending on the environmment that this code is run in, the system temporary directory (and thus the directory this method creates) may be more visible that a program would like - files written to this directory may be read or overwritten by hostile programs running on the same machine.

        This method assumes that the temporary volume is writable, has free inodes and free blocks, and that it will not be called thousands of times per second.

        equivalent: .

        Returns:
        the newly-created directory
        Throws:
        - if the directory could not be created
      • touch

        @Beta
        public static void  file)
                          throws 
        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:
        - if an I/O error occurs
      • createParentDirs

        @Beta
        public static void  file)
                                     throws 
        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:
        - 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
      • move

        @Beta
        public static void  from,
                                 to)
                         throws 
        Moves a file from one path to another. This method can rename a file and/or move it to a different directory. In either case to must be the target path for the file itself; not just the new name for the file or the path to the new parent directory.

        equivalent: .

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

        @Beta
        
        public static   file,
                                            charset)
                                    throws 
        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 for helpful predefined constants
        Returns:
        the first line, or null if the file is empty
        Throws:
        - if an I/O error occurs
      • readLines

        @Beta
        public static <>  file,
                                              charset)
                                      throws 
        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().

        equivalent: .

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

        @Beta
        
        
        public static <T> T  file,
                                       charset,
                                      LineProcessor<T> callback)
                               throws 
        Deprecated.
        Prefer asCharSource(file, charset).readLines(callback). This method is scheduled to be removed in October 2019.
        Streams lines from a , 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 for helpful predefined constants
        callback - the LineProcessor to use to handle the lines
        Returns:
        the output of processing the lines
        Throws:
        - if an I/O error occurs
      • readBytes

        @Beta
        
        
        public static <T> T  file,
                                      ByteProcessor<T> processor)
                               throws 
        Deprecated.
        Prefer asByteSource(file).read(processor). This method is scheduled to be removed in October 2019.
        Process the bytes of a file.

        (If this seems too complicated, maybe you're looking for toByteArray(java.io.File).)

        Parameters:
        file - the file to read
        processor - the object to which the bytes of the file are passed.
        Returns:
        the result of the byte processor
        Throws:
        - if an I/O error occurs
      • hash

        @Beta
        
        public static  file,
                                    HashFunction hashFunction)
                             throws 
        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:
        - if an I/O error occurs
        Since:
        12.0
      • map

        @Beta
        public static   file)
                                    throws 
        Fully maps a file read-only in to memory as per .

        Files are mapped from offset 0 to its length.

        This only works for files ≤ bytes.

        Parameters:
        file - the file to map
        Returns:
        a read-only buffer reflecting file
        Throws:
        - if the file does not exist
        - if an I/O error occurs
        Since:
        2.0
        See Also:
      • map

        @Beta
        public static   file,
                                            mode)
                                    throws 
        Fully maps a file in to memory as per using the requested .

        Files are mapped from offset 0 to its length.

        This only works for files ≤ bytes.

        Parameters:
        file - the file to map
        mode - the mode to use when mapping file
        Returns:
        a buffer reflecting file
        Throws:
        - if the file does not exist
        - if an I/O error occurs
        Since:
        2.0
        See Also:
      • map

        @Beta
        public static   file,
                                            mode,
                                           long size)
                                    throws 
        Maps a file in to memory as per using the requested .

        Files are mapped from offset 0 to size.

        If the mode is and the file does not exist, it will be created with the requested size. Thus this method is useful for creating memory mapped files which do not yet exist.

        This only works for files ≤ bytes.

        Parameters:
        file - the file to map
        mode - the mode to use when mapping file
        Returns:
        a buffer reflecting file
        Throws:
        - if an I/O error occurs
        Since:
        2.0
        See Also:
      • simplifyPath

        @Beta
        public static   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   fullName)
        Returns the 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 . It does not account for any filesystem-specific behavior that the 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 .

        Since:
        11.0
      • getNameWithoutExtension

        @Beta
        public static   file)
        Returns the file name without its 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 > fileTraverser()
        Returns a Traverser instance for the file and directory tree. The returned traverser starts from a 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 passed to one of the Traverser methods does not exist or is not a directory, no exception will be thrown and the returned 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
      • isDirectory

        @Beta
        public static > isDirectory()
        Returns a predicate that returns the result of on input files.
        Since:
        15.0
      • isFile

        @Beta
        public static > isFile()
        Returns a predicate that returns the result of on input files.
        Since:
        15.0