Java Reference
In-Depth Information
Working with File Attributes
The
File
class contains methods that let you get/set attributes of files and directories in a limited ways. You can set
a file as read-only, readable, writable, and executable using the
setReadOnly()
,
setReadable()
,
setWritable
(), and
setExecutable()
methods, respectively. You can use the
lastModified()
and
setLastModified()
methods to get
and set the last modified date and time of a file. You can check if a file is hidden using the
isHidden()
method. Note
that the
File
class does not contain a
setHidden()
method as the definition of a hidden file is platform-dependent.
■
I will discuss working with file attributes using the new Input/Output 2 (nIO.2) apI in Chapter 10. nIO.2 has
extensive support for file attributes.
Tip
Copying a File
The
File
class does not provide a method to copy a file. To copy a file, you must create a new file, read the content
from the original file, and write it into the new file. I will discuss how to copy the contents of a file into another file later
in this chapter, after I discuss the input and output streams. The NIO 2.0 API, which was added in Java 7, provides a
direct way to copy a file contents and its attributes. Please refer to Chapter 10 for more details.
Knowing the Size of a File
You can get the size of a file in bytes using the
length()
method of the
File
class.
File myFile = new File("myfile.txt");
long fileLength = myFile.length();
If a
File
object represents a non-existent file, the
length()
method returns zero. If it is a directory name, the
return value is not specified. Note that the return type of the
length()
method is
long
, not
int
.
Listing All Files and Directories
You can get a list of the available root directories in a file system by using the
listRoots() static
method of the
File
class. It returns an array of
File
objects.
// Get the list of all root directories
File[] roots = File.listRoots();
Root directories are different across platforms. On Windows, you have a root directory for each drive (e.g.
C:\
,
A:\
,
D:\
, etc.). On UNIX, you have a single root directory represented by a forward slash.
Listing 7-3 illustrates how to get the root directories on a machine. The output is shown when this program was
run on Windows. You may get a different output when you run this program on your machine. The output will depend
on the operating system and the drives that are attached to your machine.