Java Directories example

Java Directories example


DirectoryStream

• To iterate over the entries in a directory
• Scales to large directories
• Optional filter to decide if entries should be accepted or filtered
• Built-in filters to match file names using glob or regular expression

Path dir = Path.get("mydir");
DirectoryStream stream = dir.newDirectoryStream("*.java");
try {
for (DirectoryEntry entry: stream) {
System.out.println(entry.getName());
}
} finally {
stream.close();
}


Path dir = Path.get("mydir");
Files.withDirectory(dir, "*.java", new DirectoryAction() {
public void invoke(DirectoryEntry entry) {
System.out.println(entry.getName());
}
});

DirectoryStreamFilters

• Factory methods for useful filters
• newContentTypeFilter
• Accept entry based on its MIME type
• Use installed file type detectors
• Combine filters into simple expressions

Files.walkFileTree utility method

• Recursively descends directory hierarchy rooted at starting file
• Easy to use internal iterator
• FileVisitor invoked for each directory/file in hierarchy
• Options to control if symbolic links are followed, maximum depth...
• Use to implement recursive copy, move, delete, chmod...


newFileAttributeView method

• selects view by class literal that works as type-token
• method returns instance of view
BasicFileAttributeView view =
file.newFileAttributeView(BasicFileAttributeView.class, true);
// bulk read of basic attributes
BasicFileAttributes attrs = view.readAttributes();



DosFileAttributeView

• Provides access to legacy DOS attributes
• Implementable "server-side" on non-Windows platforms
AclFileAttributeView
• Provides access to Access Control Lists (ACLs)
• Based on NFSv4 ACL model
NamedAttributeView
• Provides access to attributes as name/value pairs
• Mappable to file systems that support named subfiles


PosixFileAttributeView
• Unix equivalent of stat, chmod, chown...
PosixFileAttributes attrs =
Attributes.readPosixFileAttributes(file, true);
String mode = PosixFilePermission.toString(attrs.permissions());
System.out.format("%s %s %s", mode, attrs.owner(), attr.group());
rwxrw-r-- alanb java
import static java.nio.file.attribute.PosixFilePermission.*;
Attributes.setPosixFilePermissions(file,
OWNER_READ, OWNER_WRITE, GROUP_WRITE, OTHERS_READ);

File change notification

WatchService watcher = FileSystems.getDefault().newWatchService();
Set<StandardWatchEventType> events =
EnumSet.of(ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
WatchKey key = dir.register(watcher, events);
for (;;) {
// wait for key to be signalled
key = watcher.take();
// process events
for (WatchEvent<?> ev: key.pollEvents()) {
if (event.getType() == ENTRY_MODIFY) {
:
}
}
// reset key
key.reset();
}

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations