Java Reference
In-Depth Information
Chapter 9
Accessing Files and Directories
WHAT YOU WILL LEARN IN THIS CHAPTER
• How you can access the file system on your computer
• How you can inspect files and directories
• How to create new files and directories
• How to move and copy files and directories
• How you can move and copy a directory and its contents
• How you can examine the contents of a directory tree
In this chapter, you explore how you identify, access, and manipulate files and directories (sometimes referred
to as folders) on your hard drive. This includes the ability to create, copy, move, and delete files and director-
ies.
You learn how you read and write files starting in the next chapter. Java has more than one way to work
with files and directories. The original capability came with JDK 1.0. This was augmented in JDK 1.4 with
NIO (New I/O). I only discuss the latest and greatest facility for file operations referred to as NIO2 that was
introduced in JDK 7.
ACCESSING THE FILE SYSTEM
The starting point for working with files and directories is a
java.nio.file.FileSystem
object. A
FileSystem
object encapsulates the file storage system on your computer. What this storage system consists
of and how it is organized depends on the operating system you are using. The
FileSystem
class has no
public constructors so you need another way to create such an object.
The
java.nio.file.FileSystems
class defines static factory methods for file systems. You can obtain
the
FileSystem
object that encapsulates the storage system on your machine by calling the
getDefault()
method that is defined in the
FileSystems
class, like this:
FileSystem fileSystem = FileSystems.getDefault();
The
fileSystem
object encapsulates the default file system on your computer. You can use this object to
access the files and directories within the file system.
After you have a
FileSystem
object representing the file system on your machine, you can identify the
devices and partitions within it as
java.nio.FileStore
objects. To obtain the file stores on your computer,
you call
getFileStores()
for the
FileSystem
object: