com.google.common.io
Class Files

java.lang.Object
  extended by com.google.common.io.Files

public final class Files
extends Object

Provides utility methods for working with files.

All method parameters must be non-null unless documented otherwise.

Since:
2009.09.15 tentative
Author:
Chris Nokleberg

Method Summary
static void append(CharSequence from, File to, Charset charset)
          Appends a character sequence (such as a string) to a file using the given character set.
static void copy(File from, Charset charset, Appendable to)
          Copies all characters from a file to an appendable object, using the given character set.
static
<W extends Appendable & Closeable>
void
copy(File from, Charset charset, OutputSupplier<W> to)
          Copies all characters from a file to a Appendable & Closeable object supplied by a factory, using the given character set.
static void copy(File from, File to)
          Copies all the bytes from one file to another.
static void copy(File from, OutputStream to)
          Copies all bytes from a file to an output stream.
static void copy(File from, OutputSupplier<? extends OutputStream> to)
          Copies all bytes from a file to an OutputStream supplied by a factory.
static void copy(InputSupplier<? extends InputStream> from, File to)
          Copies to a file all bytes from an InputStream supplied by a factory.
static
<R extends Readable & Closeable>
void
copy(InputSupplier<R> from, File to, Charset charset)
          Copies to a file all characters from a Readable and Closeable object supplied by a factory, using the given character set.
static File createTempDir()
          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.
static void deleteDirectoryContents(File directory)
          Deletes all the files within a directory.
static void deleteRecursively(File file)
          Deletes a file or directory and all contents recursively.
static boolean equal(File file1, File file2)
          Returns true if the files contains the same bytes.
static long getChecksum(File file, Checksum checksum)
          Computes and returns the checksum value for a file.
static byte[] getDigest(File file, MessageDigest md)
          Computes and returns the digest value for a file.
static MappedByteBuffer map(File file)
          Fully maps a file read-only in to memory as per FileChannel.map(java.nio.channels.FileChannel.MapMode, long, long).
static MappedByteBuffer map(File file, FileChannel.MapMode mode)
          Fully maps a file in to memory as per FileChannel.map(java.nio.channels.FileChannel.MapMode, long, long) using the requested FileChannel.MapMode.
static MappedByteBuffer map(File file, FileChannel.MapMode mode, long size)
          Maps a file in to memory as per FileChannel.map(java.nio.channels.FileChannel.MapMode, long, long) using the requested FileChannel.MapMode.
static void move(File from, File to)
          Moves the file from one path to another.
static InputSupplier<FileInputStream> newInputStreamSupplier(File file)
          Returns a factory that will supply instances of FileInputStream that read from a file.
static OutputSupplier<FileOutputStream> newOutputStreamSupplier(File file)
          Returns a factory that will supply instances of FileOutputStream that write to a file.
static OutputSupplier<FileOutputStream> newOutputStreamSupplier(File file, boolean append)
          Returns a factory that will supply instances of FileOutputStream that write to or append to a file.
static BufferedReader newReader(File file, Charset charset)
          Returns a buffered reader that reads from a file using the given character set.
static InputSupplier<InputStreamReader> newReaderSupplier(File file, Charset charset)
          Returns a factory that will supply instances of InputStreamReader that read a file using the given character set.
static BufferedWriter newWriter(File file, Charset charset)
          Returns a buffered writer that writes to a file using the given character set.
static OutputSupplier<OutputStreamWriter> newWriterSupplier(File file, Charset charset)
          Returns a factory that will supply instances of OutputStreamWriter that write to a file using the given character set.
static OutputSupplier<OutputStreamWriter> newWriterSupplier(File file, Charset charset, boolean append)
          Returns a factory that will supply instances of OutputStreamWriter that write to or append to a file using the given character set.
static
<T> T
readBytes(File file, ByteProcessor<T> processor)
          Process the bytes of a file.
static String readFirstLine(File file, Charset charset)
          Reads the first line from a file.
static List<String> readLines(File file, Charset charset)
          Reads all of the lines from a file.
static
<T> T
readLines(File file, Charset charset, LineProcessor<T> callback)
          Streams lines from a File, stopping when our callback returns false, or we have read all of the lines.
static byte[] toByteArray(File file)
          Reads all bytes from a file into a byte array.
static String toString(File file, Charset charset)
          Reads all characters from a file into a String, using the given character set.
static void touch(File 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, File to)
          Overwrites a file with the contents of a byte array.
static void write(CharSequence from, File to, Charset charset)
          Writes a character sequence (such as a string) to a file using the given character set.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

newReader

public static BufferedReader newReader(File file,
                                       Charset charset)
                                throws FileNotFoundException
Returns a buffered reader that reads from a file using the given character set.

Parameters:
file - the file to read from
charset - the character set used when writing the file
Returns:
the buffered reader
Throws:
FileNotFoundException

newWriter

public static BufferedWriter newWriter(File file,
                                       Charset charset)
                                throws FileNotFoundException
Returns a buffered writer that writes to a file using the given character set.

Parameters:
file - the file to write to
charset - the character set used when writing the file
Returns:
the buffered writer
Throws:
FileNotFoundException

newInputStreamSupplier

public static InputSupplier<FileInputStream> newInputStreamSupplier(File file)
Returns a factory that will supply instances of FileInputStream that read from a file.

Parameters:
file - the file to read from
Returns:
the factory

newOutputStreamSupplier

public static OutputSupplier<FileOutputStream> newOutputStreamSupplier(File file)
Returns a factory that will supply instances of FileOutputStream that write to a file.

Parameters:
file - the file to write to
Returns:
the factory

newOutputStreamSupplier

public static OutputSupplier<FileOutputStream> newOutputStreamSupplier(File file,
                                                                       boolean append)
Returns a factory that will supply instances of FileOutputStream that write to or append to a file.

Parameters:
file - the file to write to
append - if true, the encoded characters will be appended to the file; otherwise the file is overwritten
Returns:
the factory

newReaderSupplier

public static InputSupplier<InputStreamReader> newReaderSupplier(File file,
                                                                 Charset charset)
Returns a factory that will supply instances of InputStreamReader that read a file using the given character set.

Parameters:
file - the file to read from
charset - the character set used when reading the file
Returns:
the factory

newWriterSupplier

public static OutputSupplier<OutputStreamWriter> newWriterSupplier(File file,
                                                                   Charset charset)
Returns a factory that will supply instances of OutputStreamWriter that write to a file using the given character set.

Parameters:
file - the file to write to
charset - the character set used when writing the file
Returns:
the factory

newWriterSupplier

public static OutputSupplier<OutputStreamWriter> newWriterSupplier(File file,
                                                                   Charset charset,
                                                                   boolean append)
Returns a factory that will supply instances of OutputStreamWriter that write to or append to a file using the given character set.

Parameters:
file - the file to write to
charset - the character set used when writing the file
append - if true, the encoded characters will be appended to the file; otherwise the file is overwritten
Returns:
the factory

toByteArray

public static byte[] toByteArray(File file)
                          throws IOException
Reads all bytes from a file into a byte array.

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

toString

public static String toString(File file,
                              Charset charset)
                       throws IOException
Reads all characters from a file into a String, using the given character set.

Parameters:
file - the file to read from
charset - the character set used when reading the file
Returns:
a string containing all the characters from the file
Throws:
IOException - if an I/O error occurs

copy

public static void copy(InputSupplier<? extends InputStream> from,
                        File to)
                 throws IOException
Copies to a file all bytes from an InputStream supplied by a factory.

Parameters:
from - the input factory
to - the destination file
Throws:
IOException - if an I/O error occurs

write

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

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

copy

public static void copy(File from,
                        OutputSupplier<? extends OutputStream> to)
                 throws IOException
Copies all bytes from a file to an OutputStream supplied by a factory.

Parameters:
from - the source file
to - the output factory
Throws:
IOException - if an I/O error occurs

copy

public static void copy(File from,
                        OutputStream to)
                 throws IOException
Copies all bytes from a file to an output stream.

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

copy

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

Parameters:
from - the source file
to - the destination file
Throws:
IOException - if an I/O error occurs

copy

public static <R extends Readable & Closeable> void copy(InputSupplier<R> from,
                                                        File to,
                                                        Charset charset)
                 throws IOException
Copies to a file all characters from a Readable and Closeable object supplied by a factory, using the given character set.

Parameters:
from - the readable supplier
to - the destination file
charset - the character set used when writing the file
Throws:
IOException - if an I/O error occurs

write

public static void write(CharSequence from,
                         File to,
                         Charset charset)
                  throws IOException
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 character set used when writing the file
Throws:
IOException - if an I/O error occurs

append

public static void append(CharSequence from,
                          File to,
                          Charset charset)
                   throws IOException
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 character set used when writing the file
Throws:
IOException - if an I/O error occurs

copy

public static <W extends Appendable & Closeable> void copy(File from,
                                                          Charset charset,
                                                          OutputSupplier<W> to)
                 throws IOException
Copies all characters from a file to a Appendable & Closeable object supplied by a factory, using the given character set.

Parameters:
from - the source file
charset - the character set used when reading the file
to - the appendable supplier
Throws:
IOException - if an I/O error occurs

copy

public static void copy(File from,
                        Charset charset,
                        Appendable to)
                 throws IOException
Copies all characters from a file to an appendable object, using the given character set.

Parameters:
from - the source file
charset - the character set used when reading the file
to - the appendable object
Throws:
IOException - if an I/O error occurs

equal

public static boolean equal(File file1,
                            File file2)
                     throws IOException
Returns true if the files contains the same bytes.

Throws:
IOException - if an I/O error occurs

createTempDir

public static File createTempDir()
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 File.createTempFile(String, String) 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.

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.

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

touch

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

move

public static void move(File from,
                        File to)
                 throws IOException
Moves the file from one path to another. This method can rename a file or move it to a different directory, like the Unix mv command.

Parameters:
from - the source file
to - the destination file
Throws:
IOException - if an I/O error occurs

deleteDirectoryContents

public static void deleteDirectoryContents(File directory)
                                    throws IOException
Deletes all the files within a directory. Does not delete the directory itself.

If the file argument is a symbolic link or there is a symbolic link in the path leading to the directory, this method will do nothing. Symbolic links within the directory are not followed.

Parameters:
directory - the directory to delete the contents of
Throws:
IllegalArgumentException - if the argument is not a directory
IOException - if an I/O error occurs
See Also:
deleteRecursively(java.io.File)

deleteRecursively

public static void deleteRecursively(File file)
                              throws IOException
Deletes a file or directory and all contents recursively.

If the file argument is a symbolic link the link will be deleted but not the target of the link. If the argument is a directory, symbolic links within the directory will not be followed.

Parameters:
file - the file to delete
Throws:
IOException - if an I/O error occurs
See Also:
deleteDirectoryContents(java.io.File)

readFirstLine

public static String readFirstLine(File file,
                                   Charset charset)
                            throws IOException
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 character set used when writing the file
Returns:
the first line, or null if the file is empty
Throws:
IOException - if an I/O error occurs

readLines

public static List<String> readLines(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.

Parameters:
file - the file to read from
charset - the character set used when writing the file
Returns:
a mutable List containing all the lines
Throws:
IOException - if an I/O error occurs

readLines

public static <T> T readLines(File file,
                              Charset charset,
                              LineProcessor<T> callback)
                   throws IOException
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 character set used when writing the file
callback - the LineProcessor to use to handle the lines
Returns:
the output of processing the lines
Throws:
IOException - if an I/O error occurs

readBytes

public static <T> T readBytes(File file,
                              ByteProcessor<T> processor)
                   throws IOException
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:
IOException - if an I/O error occurs

getChecksum

public static long getChecksum(File file,
                               Checksum checksum)
                        throws IOException
Computes and returns the checksum value for a file. The checksum object is reset when this method returns successfully.

Parameters:
file - the file to read
checksum - the checksum object
Returns:
the result of Checksum.getValue() after updating the checksum object with all of the bytes in the file
Throws:
IOException - if an I/O error occurs

getDigest

public static byte[] getDigest(File file,
                               MessageDigest md)
                        throws IOException
Computes and returns the digest value for a file. The digest object is reset when this method returns successfully.

Parameters:
file - the file to read
md - the digest object
Returns:
the result of MessageDigest.digest() after updating the digest object with all of the bytes in this file
Throws:
IOException - if an I/O error occurs

map

public static MappedByteBuffer map(File file)
                            throws IOException
Fully maps a file read-only in to memory as per FileChannel.map(java.nio.channels.FileChannel.MapMode, long, long).

Files are mapped from offset 0 to its length.

This only works for files <= Integer.MAX_VALUE bytes.

Parameters:
file - the file to map
Returns:
a read-only buffer reflecting file
Throws:
FileNotFoundException - if the file does not exist
IOException - if an I/O error occurs
Since:
2010.01.04 tentative
See Also:
FileChannel.map(MapMode, long, long)

map

public static MappedByteBuffer map(File file,
                                   FileChannel.MapMode mode)
                            throws IOException
Fully maps a file in to memory as per FileChannel.map(java.nio.channels.FileChannel.MapMode, long, long) using the requested FileChannel.MapMode.

Files are mapped from offset 0 to its length.

This only works for files <= Integer.MAX_VALUE bytes.

Parameters:
file - the file to map
mode - the mode to use when mapping file
Returns:
a buffer reflecting file
Throws:
FileNotFoundException - if the file does not exist
IOException - if an I/O error occurs
Since:
2010.01.04 tentative
See Also:
FileChannel.map(MapMode, long, long)

map

public static MappedByteBuffer map(File file,
                                   FileChannel.MapMode mode,
                                   long size)
                            throws FileNotFoundException,
                                   IOException
Maps a file in to memory as per FileChannel.map(java.nio.channels.FileChannel.MapMode, long, long) using the requested FileChannel.MapMode.

Files are mapped from offset 0 to size.

If the mode is FileChannel.MapMode.READ_WRITE 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 <= Integer.MAX_VALUE bytes.

Parameters:
file - the file to map
mode - the mode to use when mapping file
Returns:
a buffer reflecting file
Throws:
IOException - if an I/O error occurs
FileNotFoundException
Since:
2010.01.04 tentative
See Also:
FileChannel.map(MapMode, long, long)