liveBook · Manning

Files.readAttributes

As explained in 100 Java Mistakes and How to Avoid Them

Files.readAttributes is a Java NIO method that reads a filesystem entry's attributes in a single operation and returns them as an attribute view or map.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains one-query consistency and its limits, but stops short of guaranteeing stability during later file reads.
Examples
Uses a getFileSize method that returns -1 for non-regular files and otherwise returns BasicFileAttributes.size().
What it assumes
Assumes familiarity with Java NIO Paths, Files methods, regular files, and checked I/O exceptions.
What you can do after
Apply it via Java NIO to obtain related filesystem attributes in one query and avoid a narrow replacement race.
How it connects
Connects filesystem attributes with regular-file checks, file size, filesystem queries, and concurrent file changes.

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.