Java Reference
In-Depth Information
•
It added an API that lets you walk through a file tree. You can perform a file operation on a
node as you walk through the file tree.
•
It supports asynchronous I/O on network sockets and files.
•
It supports multicasting using a
DatagramChannel
.
Working with a File System
An object of the
FileSystem
class represents a file system in a Java program. A
FileSystem
object is used to perform
two tasks:
•
It acts as an interface between a Java program and a file system.
•
It acts as a factory for creating many types of file system-related objects and services.
A
FileSystem
object is platform-dependent. You do not create an object of the
FileSystem
class directly.
To obtain the default
FileSystem
object for a platform, you need to use the
getDefault()
static method of the
FileSystems
class as follows:
// Create the platform-specific default file system object
FileSystem fs = FileSystems.getDefault();
Typically, a file system consists of one or more file stores. A file store provides storage for files. The
getFileStores()
method of the
FileSystem
class returns an
Iterator
for the
FileStore
objects.
A file system may be represented differently on different platforms. One platform may represent a file system in
a single hierarchy of files with one top-level root directory, whereas another may represent it in multiple hierarchies
of files with multiple top-level directories. The
getRootDirectories()
method of the
FileSystem
class returns an
iterator of
Path
objects, which represent paths to all top-level directories. I will discuss the
Path
class in detail in the
next section.
You can use the
isReadOnly()
method of the
FileSystem
object to test if it only allows read-only access to the
file stores. You will work with the
FileSystem
class in subsequent sections to create the file system-related objects
and services.
Listing 10-1 demonstrates how to use a
FileSystem
object. It uses the default file system for the platform. The
output shows the file system information when the program was run on Windows; you may get a different output
when you run the program.
Listing 10-1.
Retrieving Information About a File System
// FileSystemTest.java
package com.jdojo.nio2;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.io.IOException;
public class FileSystemTest {
public static void main(String[] args) {
// Create the platform-specific default file system object
FileSystem fs = FileSystems.getDefault();