Java Reference
In-Depth Information
The first output of this program demonstrates a
Path
for the folder containing this
chapter's examples. The second output demonstrates a
Path
for this example's source code
file. In both cases, we specified an absolute path.
1
// Fig. 15.2: FileAndDirectoryInfo.java
2
// File class used to obtain file and directory information.
3
4
5
6
7
8
import
java.io.IOException;
import
java.nio.file.DirectoryStream;
import
java.nio.file.Files;
import
java.nio.file.Path;
import
java.nio.file.Paths;
import
java.util.Scanner;
9
10
public class
FileAndDirectoryInfo
11
{
12
public static void
main(String[] args)
throws
IOException
13
{
14
Scanner input =
new
Scanner(System.in);
15
16
System.out.println(
"Enter file or directory name:"
);
17
18
// create Path object based on user input
Path path = Paths.get(input.nextLine());
19
20
21
if
(
Files.exists(path)
)
// if path exists, output info about it
22
{
23
// display file (or directory) information
24
System.out.printf(
"%n%s exists%n"
,
path.getFileName()
);
25
System.out.printf(
"%s a directory%n"
,
26
Files.isDirectory(path)
?
"Is"
: "
Is not"
);
27
System.out.printf(
"%s an absolute path%n"
,
28
path.isAbsolute()
?
"Is"
:
"Is not"
);
29
System.out.printf(
"Last modified: %s%n"
,
30
Files.getLastModifiedTime(path)
Files.size(path)
path
);
31
System.out.printf(
"Size: %s%n"
,
);
32
System.out.printf(
"Path: %s%n"
,
);
33
System.out.printf(
"Absolute path: %s%n"
,
path.toAbsolutePath()
);
34
35
if
(
Files.isDirectory(path)
)
// output directory listing
36
{
37
System.out.printf(
"%nDirectory contents:%n"
);
38
39
// object for iterating through a directory's contents
DirectoryStream<Path> directoryStream =
Files.newDirectoryStream(path);
40
41
42
43
for
(Path p : directoryStream)
44
System.out.println(p);
45
}
46
}
47
else
// not file or directory, output error message
48
{
Fig. 15.2
|
File
class used to obtain file and directory information
. (Part 1 of 2.)