In Java, Files.readAttributes reads several attributes of a file in one operation. That is faster than separate calls and gives a consistent snapshot.
One overload takes a class such as BasicFileAttributes.class and returns a typed object with methods like size() and isDirectory(). The other takes a string like "size,isDirectory" or "basic:*" and returns a Map from names to values.
A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.readAttributes(...), after import java.nio.file.Files;. You never create a Files object.
Syntax
Typed object or map:
Java
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
Map<String, Object> map = Files.readAttributes(path, "size,lastModifiedTime");
DosFileAttributes dos = Files.readAttributes(path, DosFileAttributes.class); // Windows
Call
What it does
BasicFileAttributes.class
Size, times, and type; works everywhere.
DosFileAttributes.class
Adds readonly, hidden, system, archive.
PosixFileAttributes.class
Adds owner, group, permissions.
"basic:*"
Every basic attribute as a map.
Since Java 7. The typed result is a snapshot: it does not change when the file changes later.
Library declarations
Java
public static <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException
public static Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException
Parameters
Parameter
Description
path
The file to inspect.
type
Which attributes interface to read.
attributes
[view:]name,name or [view:]*.
options
NOFOLLOW_LINKS to read a link itself.
Return Value
Return Value
Description
A
(Class overload) The attributes object.
Map<String, Object>
(String overload) Names without the view prefix, mapped to values.