Files.readAttributes reads several filesystem properties through one query and returns them together. Checking the returned attributes avoids a change between separate tests such as isRegularFile() and size(). section 9.11
Read the file type and size together
BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);\nif (!attributes.isRegularFile()) return -1;\nreturn attributes.size();\n\nThis prevents another process from replacing a regular file with a directory between separate filesystem queries. It does not guarantee that a later file read will observe the same size; the file can still change after the attributes query. section 9.11
static long getFileSize(Path path) throws IOException {
BasicFileAttributes attributes = Files.readAttributes( #1
path, BasicFileAttributes.class);
if (!attributes.isRegularFile()) return -1;
return attributes.size();
}
Use the focused Java example to compare attribute retrieval with separate Files queries. section 9.11
