Class Files
- java.lang.Object
-
- com.google.common.io.Files
-
@GwtIncompatible public final class Files extends java.lang.Object
Provides utility methods for working with files.Pathusers will find similar utilities inMoreFilesand the JDK'sFilesclass.- Since:
- 1.0
- Author:
- Chris Nokleberg, Colin Decker
-
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static voidappend(java.lang.CharSequence from, java.io.File to, java.nio.charset.Charset charset)Deprecated.PreferasCharSink(to, charset, FileWriteMode.APPEND).write(from).static ByteSinkasByteSink(java.io.File file, FileWriteMode... modes)Returns a newByteSinkfor writing bytes to the given file.static ByteSourceasByteSource(java.io.File file)Returns a newByteSourcefor reading bytes from the given file.static CharSinkasCharSink(java.io.File file, java.nio.charset.Charset charset, FileWriteMode... modes)Returns a newCharSinkfor writing character data to the given file using the given character set.static CharSourceasCharSource(java.io.File file, java.nio.charset.Charset charset)Returns a newCharSourcefor reading character data from the given file using the given character set.static voidcopy(java.io.File from, java.io.File to)Copies all the bytes from one file to another.static voidcopy(java.io.File from, java.io.OutputStream to)Copies all bytes from a file to an output stream.static voidcopy(java.io.File from, java.nio.charset.Charset charset, java.lang.Appendable to)Deprecated.PreferasCharSource(from, charset).copyTo(to).static voidcreateParentDirs(java.io.File file)Creates any necessary but nonexistent parent directories of the specified file.static java.io.FilecreateTempDir()Deprecated.For Android users, see the Data and File Storage overview to select an appropriate temporary directory (perhapscontext.getCacheDir()), and create your own directory under that.static booleanequal(java.io.File file1, java.io.File file2)Returns true if the given files exist, are not directories, and contain the same bytes.static Traverser<java.io.File>fileTraverser()Returns aTraverserinstance for the file and directory tree.static java.lang.StringgetFileExtension(java.lang.String fullName)Returns the file extension for the given file name, or the empty string if the file has no extension.static java.lang.StringgetNameWithoutExtension(java.lang.String file)Returns the file name without its file extension or path.static HashCodehash(java.io.File file, HashFunction hashFunction)Deprecated.PreferasByteSource(file).hash(hashFunction).static Predicate<java.io.File>isDirectory()Returns a predicate that returns the result ofFile.isDirectory()on input files.static Predicate<java.io.File>isFile()Returns a predicate that returns the result ofFile.isFile()on input files.static java.nio.MappedByteBuffermap(java.io.File file)Fully maps a file read-only in to memory as perFileChannel.map(java.nio.channels.FileChannel.MapMode, long, long).static java.nio.MappedByteBuffermap(java.io.File file, java.nio.channels.FileChannel.MapMode mode)Fully maps a file in to memory as perFileChannel.map(java.nio.channels.FileChannel.MapMode, long, long)using the requestedFileChannel.MapMode.static java.nio.MappedByteBuffermap(java.io.File file, java.nio.channels.FileChannel.MapMode mode, long size)Maps a file in to memory as perFileChannel.map(java.nio.channels.FileChannel.MapMode, long, long)using the requestedFileChannel.MapMode.static voidmove(java.io.File from, java.io.File to)Moves a file from one path to another.static java.io.BufferedReadernewReader(java.io.File file, java.nio.charset.Charset charset)Returns a buffered reader that reads from a file using the given character set.static java.io.BufferedWriternewWriter(java.io.File file, java.nio.charset.Charset charset)Returns a buffered writer that writes to a file using the given character set.static <T extends @Nullable java.lang.Object>
TreadBytes(java.io.File file, ByteProcessor<T> processor)Deprecated.PreferasByteSource(file).read(processor).static java.lang.StringreadFirstLine(java.io.File file, java.nio.charset.Charset charset)Deprecated.PreferasCharSource(file, charset).readFirstLine().static java.util.List<java.lang.String>readLines(java.io.File file, java.nio.charset.Charset charset)Reads all of the lines from a file.static <T extends @Nullable java.lang.Object>
TreadLines(java.io.File file, java.nio.charset.Charset charset, LineProcessor<T> callback)Deprecated.PreferasCharSource(file, charset).readLines(callback).static java.lang.StringsimplifyPath(java.lang.String pathname)Returns the lexically cleaned form of the path name, usually (but not always) equivalent to the original.static byte[]toByteArray(java.io.File file)Reads all bytes from a file into a byte array.static java.lang.StringtoString(java.io.File file, java.nio.charset.Charset charset)Deprecated.PreferasCharSource(file, charset).read().static voidtouch(java.io.File file)Creates an empty file or updates the last updated timestamp on the same as the unix command of the same name.static voidwrite(byte[] from, java.io.File to)Overwrites a file with the contents of a byte array.static voidwrite(java.lang.CharSequence from, java.io.File to, java.nio.charset.Charset charset)Deprecated.PreferasCharSink(to, charset).write(from).
-
-
-
Method Detail
-
newReader
public static java.io.BufferedReader newReader(java.io.File file, java.nio.charset.Charset charset) throws java.io.FileNotFoundException
Returns a buffered reader that reads from a file using the given character set.Pathequivalent:Files.newBufferedReader(java.nio.file.Path, Charset).- Parameters:
file- the file to read fromcharset- the charset used to decode the input stream; seeStandardCharsetsfor helpful predefined constants- Returns:
- the buffered reader
- Throws:
java.io.FileNotFoundException
-
newWriter
public static java.io.BufferedWriter newWriter(java.io.File file, java.nio.charset.Charset charset) throws java.io.FileNotFoundException
Returns a buffered writer that writes to a file using the given character set.Pathequivalent:Files.newBufferedWriter(java.nio.file.Path, Charset, java.nio.file.OpenOption...).- Parameters:
file- the file to write tocharset- the charset used to encode the output stream; seeStandardCharsetsfor helpful predefined constants- Returns:
- the buffered writer
- Throws:
java.io.FileNotFoundException
-
asByteSource
public static ByteSource asByteSource(java.io.File file)
Returns a newByteSourcefor reading bytes from the given file.- Since:
- 14.0
-
asByteSink
public static ByteSink asByteSink(java.io.File file, FileWriteMode... modes)
Returns a newByteSinkfor writing bytes to the given file. The givenmodescontrol how the file is opened for writing. When no mode is provided, the file will be truncated before writing. When theAPPENDmode is provided, writes will append to the end of the file without truncating it.- Since:
- 14.0
-
asCharSource
public static CharSource asCharSource(java.io.File file, java.nio.charset.Charset charset)
Returns a newCharSourcefor reading character data from the given file using the given character set.- Since:
- 14.0
-
asCharSink
public static CharSink asCharSink(java.io.File file, java.nio.charset.Charset charset, FileWriteMode... modes)
Returns a newCharSinkfor writing character data to the given file using the given character set. The givenmodescontrol how the file is opened for writing. When no mode is provided, the file will be truncated before writing. When theAPPENDmode is provided, writes will append to the end of the file without truncating it.- Since:
- 14.0
-
toByteArray
public static byte[] toByteArray(java.io.File file) throws java.io.IOException
Reads all bytes from a file into a byte array.Pathequivalent:Files.readAllBytes(java.nio.file.Path).- Parameters:
file- the file to read from- Returns:
- a byte array containing all the bytes from file
- Throws:
java.lang.IllegalArgumentException- if the file is bigger than the largest possible byte array (2^31 - 1)java.io.IOException- if an I/O error occurs
-
toString
@Deprecated @InlineMe(replacement="Files.asCharSource(file, charset).read()", imports="com.google.common.io.Files") public static java.lang.String toString(java.io.File file, java.nio.charset.Charset charset) throws java.io.IOException
Deprecated.PreferasCharSource(file, charset).read().Reads all characters from a file into aString, using the given character set.- Parameters:
file- the file to read fromcharset- the charset used to decode the input stream; seeStandardCharsetsfor helpful predefined constants- Returns:
- a string containing all the characters from the file
- Throws:
java.io.IOException- if an I/O error occurs
-
write
public static void write(byte[] from, java.io.File to) throws java.io.IOException
Overwrites a file with the contents of a byte array.Pathequivalent:Files.write(java.nio.file.Path, byte[], java.nio.file.OpenOption...).- Parameters:
from- the bytes to writeto- the destination file- Throws:
java.io.IOException- if an I/O error occurs
-
write
@Deprecated @InlineMe(replacement="Files.asCharSink(to, charset).write(from)", imports="com.google.common.io.Files") public static void write(java.lang.CharSequence from, java.io.File to, java.nio.charset.Charset charset) throws java.io.IOException
Deprecated.PreferasCharSink(to, charset).write(from).Writes a character sequence (such as a string) to a file using the given character set.- Parameters:
from- the character sequence to writeto- the destination filecharset- the charset used to encode the output stream; seeStandardCharsetsfor helpful predefined constants- Throws:
java.io.IOException- if an I/O error occurs
-
copy
public static void copy(java.io.File from, java.io.OutputStream to) throws java.io.IOException
Copies all bytes from a file to an output stream.Pathequivalent:Files.copy(java.nio.file.Path, OutputStream).- Parameters:
from- the source fileto- the output stream- Throws:
java.io.IOException- if an I/O error occurs
-
copy
public static void copy(java.io.File from, java.io.File to) throws java.io.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,
tomay not be a complete copy offrom. If you need to guard against those conditions, you should employ other file-level synchronization.Warning: If
torepresents an existing file, that file will be overwritten with the contents offrom. Iftoandfromrefer to the same file, the contents of that file will be deleted.Pathequivalent:Files.copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...).- Parameters:
from- the source fileto- the destination file- Throws:
java.io.IOException- if an I/O error occursjava.lang.IllegalArgumentException- iffrom.equals(to)
-
copy
@Deprecated @InlineMe(replacement="Files.asCharSource(from, charset).copyTo(to)", imports="com.google.common.io.Files") public static void copy(java.io.File from, java.nio.charset.Charset charset, java.lang.Appendable to) throws java.io.IOException
Deprecated.PreferasCharSource(from, charset).copyTo(to).Copies all characters from a file to an appendable object, using the given character set.- Parameters:
from- the source filecharset- the charset used to decode the input stream; seeStandardCharsetsfor helpful predefined constantsto- the appendable object- Throws:
java.io.IOException- if an I/O error occurs
-
append
@Deprecated @InlineMe(replacement="Files.asCharSink(to, charset, FileWriteMode.APPEND).write(from)", imports={"com.google.common.io.FileWriteMode","com.google.common.io.Files"}) public static void append(java.lang.CharSequence from, java.io.File to, java.nio.charset.Charset charset) throws java.io.IOException
Deprecated.PreferasCharSink(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 appendto- the destination filecharset- the charset used to encode the output stream; seeStandardCharsetsfor helpful predefined constants- Throws:
java.io.IOException- if an I/O error occurs
-
equal
public static boolean equal(java.io.File file1, java.io.File file2) throws java.io.IOException
Returns true if the given files exist, are not directories, and contain the same bytes.- Throws:
java.io.IOException- if an I/O error occurs
-
createTempDir
@Beta @Deprecated @J2ObjCIncompatible public static java.io.File createTempDir()
Deprecated.For Android users, see the Data and File Storage overview to select an appropriate temporary directory (perhapscontext.getCacheDir()), and create your own directory under that. (For example, you might usenew File(context.getCacheDir(), "directoryname").mkdir(), or, if you need an arbitrary number of temporary directories, you might have to generate multiple directory names in a loop untilmkdir()returnstrue.) For developers on Java 7 or later, useFiles.createTempDirectory(java.nio.file.Path, java.lang.String, java.nio.file.attribute.FileAttribute<?>...), transforming it to aFileusingtoFile()if needed. To restrict permissions as this method does, passPosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))to your call tocreateTempDirectory.Atomically creates a new directory somewhere beneath the system's temporary directory (as defined by thejava.io.tmpdirsystem property), and returns its name.The temporary directory is created with permissions restricted to the current user or, in the case of Android, the current app. If that is not possible (as is the case under the very old Android Ice Cream Sandwich release), then this method throws an exception instead of creating a directory that would be more accessible. (This behavior is new in Guava 32.0.0. Previous versions would create a directory that is more accessible, as discussed in CVE-2020-8908.)
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 callcreateTempFile, 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.
Pathequivalent:Files.createTempDirectory(java.nio.file.Path, java.lang.String, java.nio.file.attribute.FileAttribute<?>...).- Returns:
- the newly-created directory
- Throws:
java.lang.IllegalStateException- if the directory could not be created, such as if the system does not support creating temporary directories securely
-
touch
public static void touch(java.io.File file) throws java.io.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:
java.io.IOException- if an I/O error occurs
-
createParentDirs
public static void createParentDirs(java.io.File file) throws java.io.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:
java.io.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
-
move
public static void move(java.io.File from, java.io.File to) throws java.io.IOException
Moves a file from one path to another. This method can rename a file and/or move it to a different directory. In either casetomust be the target path for the file itself; not just the new name for the file or the path to the new parent directory.Pathequivalent:Files.move(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...).- Parameters:
from- the source fileto- the destination file- Throws:
java.io.IOException- if an I/O error occursjava.lang.IllegalArgumentException- iffrom.equals(to)
-
readFirstLine
@Deprecated @InlineMe(replacement="Files.asCharSource(file, charset).readFirstLine()", imports="com.google.common.io.Files") @CheckForNull public static java.lang.String readFirstLine(java.io.File file, java.nio.charset.Charset charset) throws java.io.IOException
Deprecated.PreferasCharSource(file, charset).readFirstLine().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 fromcharset- the charset used to decode the input stream; seeStandardCharsetsfor helpful predefined constants- Returns:
- the first line, or null if the file is empty
- Throws:
java.io.IOException- if an I/O error occurs
-
readLines
public static java.util.List<java.lang.String> readLines(java.io.File file, java.nio.charset.Charset charset) throws java.io.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 anImmutableList, useFiles.asCharSource(file, charset).readLines().Pathequivalent:Files.readAllLines(java.nio.file.Path, Charset).- Parameters:
file- the file to read fromcharset- the charset used to decode the input stream; seeStandardCharsetsfor helpful predefined constants- Returns:
- a mutable
Listcontaining all the lines - Throws:
java.io.IOException- if an I/O error occurs
-
readLines
@Deprecated @InlineMe(replacement="Files.asCharSource(file, charset).readLines(callback)", imports="com.google.common.io.Files") @CanIgnoreReturnValue public static <T extends @Nullable java.lang.Object> T readLines(java.io.File file, java.nio.charset.Charset charset, LineProcessor<T> callback) throws java.io.IOException
Deprecated.PreferasCharSource(file, charset).readLines(callback).Streams lines from aFile, stopping when our callback returns false, or we have read all of the lines.- Parameters:
file- the file to read fromcharset- the charset used to decode the input stream; seeStandardCharsetsfor helpful predefined constantscallback- theLineProcessorto use to handle the lines- Returns:
- the output of processing the lines
- Throws:
java.io.IOException- if an I/O error occurs
-
readBytes
@Deprecated @InlineMe(replacement="Files.asByteSource(file).read(processor)", imports="com.google.common.io.Files") @CanIgnoreReturnValue public static <T extends @Nullable java.lang.Object> T readBytes(java.io.File file, ByteProcessor<T> processor) throws java.io.IOException
Deprecated.PreferasByteSource(file).read(processor).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 readprocessor- the object to which the bytes of the file are passed.- Returns:
- the result of the byte processor
- Throws:
java.io.IOException- if an I/O error occurs
-
hash
@Deprecated @InlineMe(replacement="Files.asByteSource(file).hash(hashFunction)", imports="com.google.common.io.Files") public static HashCode hash(java.io.File file, HashFunction hashFunction) throws java.io.IOException
Deprecated.PreferasByteSource(file).hash(hashFunction).Computes the hash code of thefileusinghashFunction.- Parameters:
file- the file to readhashFunction- the hash function to use to hash the data- Returns:
- the
HashCodeof all of the bytes in the file - Throws:
java.io.IOException- if an I/O error occurs- Since:
- 12.0
-
map
public static java.nio.MappedByteBuffer map(java.io.File file) throws java.io.IOException
Fully maps a file read-only in to memory as perFileChannel.map(java.nio.channels.FileChannel.MapMode, long, long).Files are mapped from offset 0 to its length.
This only works for files ≤
Integer.MAX_VALUEbytes.- Parameters:
file- the file to map- Returns:
- a read-only buffer reflecting
file - Throws:
java.io.FileNotFoundException- if thefiledoes not existjava.io.IOException- if an I/O error occurs- Since:
- 2.0
- See Also:
FileChannel.map(MapMode, long, long)
-
map
public static java.nio.MappedByteBuffer map(java.io.File file, java.nio.channels.FileChannel.MapMode mode) throws java.io.IOException
Fully maps a file in to memory as perFileChannel.map(java.nio.channels.FileChannel.MapMode, long, long)using the requestedFileChannel.MapMode.Files are mapped from offset 0 to its length.
This only works for files ≤
Integer.MAX_VALUEbytes.- Parameters:
file- the file to mapmode- the mode to use when mappingfile- Returns:
- a buffer reflecting
file - Throws:
java.io.FileNotFoundException- if thefiledoes not existjava.io.IOException- if an I/O error occurs- Since:
- 2.0
- See Also:
FileChannel.map(MapMode, long, long)
-
map
public static java.nio.MappedByteBuffer map(java.io.File file, java.nio.channels.FileChannel.MapMode mode, long size) throws java.io.IOException
Maps a file in to memory as perFileChannel.map(java.nio.channels.FileChannel.MapMode, long, long)using the requestedFileChannel.MapMode.Files are mapped from offset 0 to
size.If the mode is
FileChannel.MapMode.READ_WRITEand the file does not exist, it will be created with the requestedsize. Thus this method is useful for creating memory mapped files which do not yet exist.This only works for files ≤
Integer.MAX_VALUEbytes.- Parameters:
file- the file to mapmode- the mode to use when mappingfile- Returns:
- a buffer reflecting
file - Throws:
java.io.IOException- if an I/O error occurs- Since:
- 2.0
- See Also:
FileChannel.map(MapMode, long, long)
-
simplifyPath
public static java.lang.String simplifyPath(java.lang.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, whichsimplifyPathwill change tob. Ifais a symlink tox,a/../bmay refer to a sibling ofx, rather than the sibling ofareferred to byb.- Since:
- 11.0
-
getFileExtension
public static java.lang.String getFileExtension(java.lang.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 byFile.getName(). It does not account for any filesystem-specific behavior that theFileAPI 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
public static java.lang.String getNameWithoutExtension(java.lang.String file)
Returns the file name without its file extension or path. This is similar to thebasenameunix 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
public static Traverser<java.io.File> fileTraverser()
Returns aTraverserinstance for the file and directory tree. The returned traverser starts from aFileand will return all files and directories it encounters.Warning:
Fileprovides 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 returnsPathinstances.If the
Filepassed to one of theTraversermethods does not exist or is not a directory, no exception will be thrown and the returnedIterablewill 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
public static Predicate<java.io.File> isDirectory()
Returns a predicate that returns the result ofFile.isDirectory()on input files.- Since:
- 15.0
-
-