Top Description Inners Constructors Methods
com.google.common.io

public final Class MoreFiles

extends Object
Class Inheritance
Annotations
@J2ktIncompatible
@GwtIncompatible
@J2ObjCIncompatible
@ElementTypesAreNonnullByDefault
Static Imports
com.google.common.base.Preconditions.checkNotNull, com.google.common.collect.Iterables.getOnlyElement, java.nio.file.LinkOption.NOFOLLOW_LINKS, java.util.Objects.requireNonNull

Static utilities for use with Path instances, intended to complement Files.

Many methods provided by Guava's Files class for java.io.File instances are now available via the JDK's java.nio.file.Files class for Path - check the JDK's class if a sibling method from Files appears to be missing from this class.

Author
Colin Decker
Since
21.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
private static class

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
private static Collection<IOException>
addException(Collection<IOException> exceptions, IOException e)

Adds the given exception to the given collection, creating the collection if it's null.

public static ByteSink
asByteSink(Path path, OpenOption... options)

Returns a view of the given path as a ByteSink.

public static ByteSource
asByteSource(Path path, OpenOption... options)

Returns a view of the given path as a ByteSource.

public static CharSink
asCharSink(Path path, Charset charset, OpenOption... options)

Returns a view of the given path as a CharSink using the given charset.

public static CharSource
asCharSource(Path path, Charset charset, OpenOption... options)

Returns a view of the given path as a CharSource using the given charset.

private static void
checkAllowsInsecure(Path path, RecursiveDeleteOption[] options)

Checks that the given options allow an insecure delete, throwing an exception if not.

private static Collection<IOException>
concat(Collection<IOException> exceptions, Collection<IOException> other)

Concatenates the contents of the two given collections of exceptions.

public static void
createParentDirectories(Path path, FileAttribute<?>... attrs)

Creates any necessary but nonexistent parent directories of the specified path.

public static void
deleteDirectoryContents(Path path, RecursiveDeleteOption... options)

Deletes all files within the directory at the given path recursively.

private static Collection<IOException>
deleteDirectoryContentsInsecure(DirectoryStream<Path> dir)

Simple, insecure method for deleting the contents of a directory for file systems that don't support SecureDirectoryStream.

private static Collection<IOException>
deleteDirectoryContentsSecure(SecureDirectoryStream<Path> dir)

Secure method for deleting the contents of a directory using SecureDirectoryStream.

public static void
deleteRecursively(Path path, RecursiveDeleteOption... options)

Deletes the file or directory at the given path recursively.

private static Collection<IOException>
deleteRecursivelyInsecure(Path path)

Insecure recursive delete for file systems that don't support SecureDirectoryStream.

private static Collection<IOException>
deleteRecursivelySecure(SecureDirectoryStream<Path> dir, Path path)

Secure recursive delete using SecureDirectoryStream.

public static boolean
equal(Path path1, Path path2)

Returns true if the files located by the given paths exist, are not directories, and contain the same bytes.

public static Traverser<Path>
fileTraverser()

Returns a Traverser instance for the file and directory tree.

private static Iterable<Path>
public static String
getFileExtension(Path path)

Returns the file extension for the file at the given path, or the empty string if the file has no extension.

public static String
getNameWithoutExtension(Path path)

Returns the file name without its file extension or path.

private static Path
getParentPath(Path path)

Returns a path to the parent directory of the given path.

public static Predicate<Path>
isDirectory(LinkOption... options)

Returns a predicate that returns the result of java.nio.file.Files#isDirectory(Path, LinkOption...) on input paths with the given link options.

private static boolean
isDirectory(SecureDirectoryStream<Path> dir, Path name, LinkOption... options)

Returns whether or not the file with the given name in the given dir is a directory.

public static Predicate<Path>
isRegularFile(LinkOption... options)

Returns a predicate that returns the result of java.nio.file.Files#isRegularFile(Path, LinkOption...) on input paths with the given link options.

public static ImmutableList<Path>
listFiles(Path dir)

Returns an immutable list of paths to the files contained in the given directory.

private static NoSuchFileException
private static void
throwDeleteFailed(Path path, Collection<IOException> exceptions)

Throws an exception indicating that one or more files couldn't be deleted when deleting path or its contents.

public static void
touch(Path path)

Like the unix command of the same name, creates an empty file or updates the last modified timestamp of the existing file at the given path to the current system time.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

MoreFilesback to summary
private MoreFiles()

Method Detail

addExceptionback to summary
private static Collection<IOException> addException(Collection<IOException> exceptions, IOException e)

Adds the given exception to the given collection, creating the collection if it's null. Returns the collection.

asByteSinkback to summary
public static ByteSink asByteSink(Path path, OpenOption... options)

Returns a view of the given path as a ByteSink.

Any open options provided are used when opening streams to the file and may affect the behavior of the returned sink and the streams it provides. See StandardOpenOption for the standard options that may be provided. Providing no options is equivalent to providing the CREATE, TRUNCATE_EXISTING and WRITE options.

asByteSourceback to summary
public static ByteSource asByteSource(Path path, OpenOption... options)

Returns a view of the given path as a ByteSource.

Any open options provided are used when opening streams to the file and may affect the behavior of the returned source and the streams it provides. See StandardOpenOption for the standard options that may be provided. Providing no options is equivalent to providing the READ option.

asCharSinkback to summary
public static CharSink asCharSink(Path path, Charset charset, OpenOption... options)

Returns a view of the given path as a CharSink using the given charset.

Any open options provided are used when opening streams to the file and may affect the behavior of the returned sink and the streams it provides. See StandardOpenOption for the standard options that may be provided. Providing no options is equivalent to providing the CREATE, TRUNCATE_EXISTING and WRITE options.

asCharSourceback to summary
public static CharSource asCharSource(Path path, Charset charset, OpenOption... options)

Returns a view of the given path as a CharSource using the given charset.

Any open options provided are used when opening streams to the file and may affect the behavior of the returned source and the streams it provides. See StandardOpenOption for the standard options that may be provided. Providing no options is equivalent to providing the READ option.

checkAllowsInsecureback to summary
private static void checkAllowsInsecure(Path path, RecursiveDeleteOption[] options) throws InsecureRecursiveDeleteException

Checks that the given options allow an insecure delete, throwing an exception if not.

concatback to summary
private static Collection<IOException> concat(Collection<IOException> exceptions, Collection<IOException> other)

Concatenates the contents of the two given collections of exceptions. If either collection is null, the other collection is returned. Otherwise, the elements of other are added to exceptions and exceptions is returned.

Annotations
@CheckForNull
createParentDirectoriesback to summary
public static void createParentDirectories(Path path, FileAttribute<?>... attrs) throws IOException

Creates any necessary but nonexistent parent directories of the specified path. Note that if this operation fails, it may have succeeded in creating some (but not all) of the necessary parent directories. The parent directory is created with the given attrs.

Exceptions
IOException:
if an I/O error occurs, or if any necessary but nonexistent parent directories of the specified file could not be created.
deleteDirectoryContentsback to summary
public static void deleteDirectoryContents(Path path, RecursiveDeleteOption... options) throws IOException

Deletes all files within the directory at the given path recursively. Does not delete the directory itself. Deletes symbolic links, not their targets (subject to the caveat below). If path itself is a symbolic link to a directory, that link is followed and the contents of the directory it targets are deleted.

If an I/O exception occurs attempting to read, open or delete any file under the given directory, this method skips that file and continues. All such exceptions are collected and, after attempting to delete all files, an IOException is thrown containing those exceptions as suppressed exceptions.

Warning: Security of recursive deletes

On a file system that supports symbolic links and does not support SecureDirectoryStream, it is possible for a recursive delete to delete files and directories that are outside the directory being deleted. This can happen if, after checking that a file is a directory (and not a symbolic link), that directory is replaced by a symbolic link to an outside directory before the call that opens the directory to read its entries.

By default, this method throws InsecureRecursiveDeleteException if it can't guarantee the security of recursive deletes. If you wish to allow the recursive deletes anyway, pass RecursiveDeleteOption#ALLOW_INSECURE to this method to override that behavior.

Exceptions
IOException:
if one or more files can't be deleted for any reason
NoSuchFileException:
if path does not exist (optional specific exception)
NotDirectoryException:
if the file at path is not a directory (optional specific exception)
InsecureRecursiveDeleteException:
if the security of recursive deletes can't be guaranteed for the file system and RecursiveDeleteOption#ALLOW_INSECURE was not specified
deleteDirectoryContentsInsecureback to summary
private static Collection<IOException> deleteDirectoryContentsInsecure(DirectoryStream<Path> dir)

Simple, insecure method for deleting the contents of a directory for file systems that don't support SecureDirectoryStream. Returns a collection of exceptions that occurred or null if no exceptions were thrown.

Annotations
@CheckForNull
deleteDirectoryContentsSecureback to summary
private static Collection<IOException> deleteDirectoryContentsSecure(SecureDirectoryStream<Path> dir)

Secure method for deleting the contents of a directory using SecureDirectoryStream. Returns a collection of exceptions that occurred or null if no exceptions were thrown.

Annotations
@CheckForNull
deleteRecursivelyback to summary
public static void deleteRecursively(Path path, RecursiveDeleteOption... options) throws IOException

Deletes the file or directory at the given path recursively. Deletes symbolic links, not their targets (subject to the caveat below).

If an I/O exception occurs attempting to read, open or delete any file under the given directory, this method skips that file and continues. All such exceptions are collected and, after attempting to delete all files, an IOException is thrown containing those exceptions as suppressed exceptions.

Warning: Security of recursive deletes

On a file system that supports symbolic links and does not support SecureDirectoryStream, it is possible for a recursive delete to delete files and directories that are outside the directory being deleted. This can happen if, after checking that a file is a directory (and not a symbolic link), that directory is replaced by a symbolic link to an outside directory before the call that opens the directory to read its entries.

By default, this method throws InsecureRecursiveDeleteException if it can't guarantee the security of recursive deletes. If you wish to allow the recursive deletes anyway, pass RecursiveDeleteOption#ALLOW_INSECURE to this method to override that behavior.

Exceptions
IOException:
if path or any file in the subtree rooted at it can't be deleted for any reason
NoSuchFileException:
if path does not exist (optional specific exception)
InsecureRecursiveDeleteException:
if the security of recursive deletes can't be guaranteed for the file system and RecursiveDeleteOption#ALLOW_INSECURE was not specified
deleteRecursivelyInsecureback to summary
private static Collection<IOException> deleteRecursivelyInsecure(Path path)

Insecure recursive delete for file systems that don't support SecureDirectoryStream. Returns a collection of exceptions that occurred or null if no exceptions were thrown.

Annotations
@CheckForNull
deleteRecursivelySecureback to summary
private static Collection<IOException> deleteRecursivelySecure(SecureDirectoryStream<Path> dir, Path path)

Secure recursive delete using SecureDirectoryStream. Returns a collection of exceptions that occurred or null if no exceptions were thrown.

Annotations
@CheckForNull
equalback to summary
public static boolean equal(Path path1, Path path2) throws IOException

Returns true if the files located by the given paths exist, are not directories, and contain the same bytes.

Exceptions
IOException:
if an I/O error occurs
Since
22.0
fileTraverserback to summary
public static Traverser<Path> fileTraverser()

Returns a Traverser instance for the file and directory tree. The returned traverser starts from a Path and will return all files and directories it encounters.

The returned traverser attempts to avoid following symbolic links to directories. However, the traverser cannot guarantee that it will not follow symbolic links to directories as it is possible for a directory to be replaced with a symbolic link between checking if the file is a directory and actually reading the contents of that directory.

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

DirectoryIteratorException may be thrown when iterating Iterable instances created by this traverser if an IOException is thrown by a call to listFiles(Path).

Example: MoreFiles.fileTraverser().depthFirstPreOrder(Paths.get("/")) may return the following paths: ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home", "/home/alice", ...]

Since
23.5
fileTreeChildrenback to summary
private static Iterable<Path> fileTreeChildren(Path dir)
getFileExtensionback to summary
public static String getFileExtension(Path path)

Returns the file extension for the file at the given path, 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 Path#getFileName. It does not account for any filesystem-specific behavior that the Path 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.

getNameWithoutExtensionback to summary
public static String getNameWithoutExtension(Path path)

Returns the file name without its file extension or path. This is similar to the basename unix command. The result does not include the '.'.

getParentPathback to summary
private static Path getParentPath(Path path)

Returns a path to the parent directory of the given path. If the path actually has a parent path, this is simple. Otherwise, we need to do some trickier things. Returns null if the path is a root or is the empty path.

Annotations
@CheckForNull
isDirectoryback to summary
public static Predicate<Path> isDirectory(LinkOption... options)

Returns a predicate that returns the result of java.nio.file.Files#isDirectory(Path, LinkOption...) on input paths with the given link options.

isDirectoryback to summary
private static boolean isDirectory(SecureDirectoryStream<Path> dir, Path name, LinkOption... options) throws IOException

Returns whether or not the file with the given name in the given dir is a directory.

isRegularFileback to summary
public static Predicate<Path> isRegularFile(LinkOption... options)

Returns a predicate that returns the result of java.nio.file.Files#isRegularFile(Path, LinkOption...) on input paths with the given link options.

listFilesback to summary
public static ImmutableList<Path> listFiles(Path dir) throws IOException

Returns an immutable list of paths to the files contained in the given directory.

Exceptions
IOException:
if an I/O error occurs
NoSuchFileException:
if the file does not exist (optional specific exception)
NotDirectoryException:
if the file could not be opened because it is not a directory (optional specific exception)
pathNotFoundback to summary
private static NoSuchFileException pathNotFound(Path path, Collection<IOException> exceptions)
Annotations
@CheckForNull
throwDeleteFailedback to summary
private static void throwDeleteFailed(Path path, Collection<IOException> exceptions) throws FileSystemException

Throws an exception indicating that one or more files couldn't be deleted when deleting path or its contents.

If there is only one exception in the collection, and it is a NoSuchFileException thrown because path itself didn't exist, then throws that exception. Otherwise, the thrown exception contains all the exceptions in the given collection as suppressed exceptions.

touchback to summary
public static void touch(Path path) throws IOException

Like the unix command of the same name, creates an empty file or updates the last modified timestamp of the existing file at the given path to the current system time.

Annotations
@SuppressWarnings:GoodTime
com.google.common.io back to summary

private final Class MoreFiles.PathByteSink

extends ByteSink
Class Inheritance

Field Summary

Modifier and TypeField and Description
private final OpenOption[]
private final Path

Constructor Summary

AccessConstructor and Description
private
PathByteSink(Path path, OpenOption... options)

Method Summary

Modifier and TypeMethod and Description
public OutputStream
openStream()

Implements abstract com.google.common.io.ByteSink.openStream.

Opens a new OutputStream for writing to this sink.
public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.
Inherited from com.google.common.io.ByteSink:
asCharSinkopenBufferedStreamwritewriteFrom

Field Detail

optionsback to summary
private final OpenOption[] options
pathback to summary
private final Path path

Constructor Detail

PathByteSinkback to summary
private PathByteSink(Path path, OpenOption... options)

Method Detail

openStreamback to summary
public OutputStream openStream() throws IOException

Implements abstract com.google.common.io.ByteSink.openStream.

Doc from com.google.common.io.ByteSink.openStream.

Opens a new OutputStream for writing to this sink. This method returns a new, independent stream each time it is called.

The caller is responsible for ensuring that the returned stream is closed.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs while opening the stream
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object.

Returns:String

a string representation of the object.

Annotations
@Override
com.google.common.io back to summary

private final Class MoreFiles.PathByteSource

extends ByteSource
Class Inheritance

Field Summary

Modifier and TypeField and Description
private static final LinkOption[]
private final boolean
private final OpenOption[]
private final Path

Constructor Summary

AccessConstructor and Description
private
PathByteSource(Path path, OpenOption... options)

Method Summary

Modifier and TypeMethod and Description
public CharSource
asCharSource(Charset charset)

Overrides com.google.common.io.ByteSource.asCharSource.

Returns a CharSource view of this byte source that decodes bytes read from this source as characters using the given Charset.
public InputStream
openStream()

Implements abstract com.google.common.io.ByteSource.openStream.

Opens a new InputStream for reading from this source.
public byte[]
read()

Overrides com.google.common.io.ByteSource.read.

Reads the full contents of this byte source as a byte array.
private BasicFileAttributes
public long
size()

Overrides com.google.common.io.ByteSource.size.

Returns the size of this source in bytes, even if doing so requires opening and traversing an entire stream.
public Optional<Long>
sizeIfKnown()

Overrides com.google.common.io.ByteSource.sizeIfKnown.

Returns the size of this source in bytes, if the size can be easily determined without actually opening the data stream.
public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.
Inherited from com.google.common.io.ByteSource:
concatconcatconcatcontentEqualscopyTocopyToemptyhashisEmptyopenBufferedStreamreadslicewrap

Field Detail

optionsback to summary
private final OpenOption[] options
pathback to summary
private final Path path

Constructor Detail

PathByteSourceback to summary
private PathByteSource(Path path, OpenOption... options)

Method Detail

asCharSourceback to summary
public CharSource asCharSource(Charset charset)

Overrides com.google.common.io.ByteSource.asCharSource.

Doc from com.google.common.io.ByteSource.asCharSource.

Returns a CharSource view of this byte source that decodes bytes read from this source as characters using the given Charset.

If CharSource#asByteSource is called on the returned source with the same charset, the default implementation of this method will ensure that the original ByteSource is returned, rather than round-trip encoding. Subclasses that override this method should behave the same way.

Annotations
@Override
openStreamback to summary
public InputStream openStream() throws IOException

Implements abstract com.google.common.io.ByteSource.openStream.

Doc from com.google.common.io.ByteSource.openStream.

Opens a new InputStream for reading from this source. This method returns a new, independent stream each time it is called.

The caller is responsible for ensuring that the returned stream is closed.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs while opening the stream
readback to summary
public byte[] read() throws IOException

Overrides com.google.common.io.ByteSource.read.

Doc from com.google.common.io.ByteSource.read.

Reads the full contents of this byte source as a byte array.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs while reading from this source
readAttributesback to summary
private BasicFileAttributes readAttributes() throws IOException
sizeback to summary
public long size() throws IOException

Overrides com.google.common.io.ByteSource.size.

Doc from com.google.common.io.ByteSource.size.

Returns the size of this source in bytes, even if doing so requires opening and traversing an entire stream. To avoid a potentially expensive operation, see sizeIfKnown.

The default implementation calls sizeIfKnown and returns the value if present. If absent, it will fall back to a heavyweight operation that will open a stream, read (or skip, if possible) to the end of the stream and return the total number of bytes that were read.

Note that for some sources that implement sizeIfKnown to provide a more efficient implementation, it is possible that this method will return a different number of bytes than would be returned by reading all of the bytes (for example, some special files may return a size of 0 despite actually having content when read).

In either case, for mutable sources such as files, a subsequent read may return a different number of bytes if the contents are changed.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs while reading the size of this source
sizeIfKnownback to summary
public Optional<Long> sizeIfKnown()

Overrides com.google.common.io.ByteSource.sizeIfKnown.

Doc from com.google.common.io.ByteSource.sizeIfKnown.

Returns the size of this source in bytes, if the size can be easily determined without actually opening the data stream.

The default implementation returns Optional#absent. Some sources, such as a file, may return a non-absent value. Note that in such cases, it is possible that this method will return a different number of bytes than would be returned by reading all of the bytes (for example, some special files may return a size of 0 despite actually having content when read).

Additionally, for mutable sources such as files, a subsequent read may return a different number of bytes if the contents are changed.

Annotations
@Override
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object.

Returns:String

a string representation of the object.

Annotations
@Override