Java Reference
In-Depth Information
46
builder.append(String.format(
"Absolute path: %s%n"
,
47
path.toAbsolutePath()));
48
49
if
(Files.isDirectory(path))
// output directory listing
50
{
51
builder.append(String.format(
"%nDirectory contents:%n"
));
52
53
// object for iterating through a directory's contents
54
DirectoryStream<Path> directoryStream =
55
Files.newDirectoryStream(path);
56
57
for
(Path p : directoryStream)
58
builder.append(String.format(
"%s%n"
, p));
59
}
60
61
outputArea.setText(builder.toString());
// display String content
62
}
63
else
// Path does not exist
64
{
65
JOptionPane.showMessageDialog(
this
, path.getFileName() +
66
" does not exist."
,
"ERROR"
,
JOptionPane.ERROR_MESSAGE
);
67
}
68
}
// end method analyzePath
69
70
// allow user to specify file or directory name
71
private
Path getFileOrDirectoryPath()
72
{
73
// configure dialog allowing selection of a file or directory
JFileChooser fileChooser =
new
JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_AND_DIRECTORIES
);
int
result = fileChooser.showOpenDialog(
this
);
74
75
76
77
78
79
// if user clicked Cancel button on dialog, return
80
if
(result ==
JFileChooser.CANCEL_OPTION
)
81
System.exit(
1
);
82
83
// return Path representing the selected file
84
return
fileChooser.getSelectedFile().toPath()
;
85
}
86
}
// end class JFileChooserDemo
Fig. 15.12
|
Demonstrating
JFileChooser
. (Part 2 of 2.)
1
// Fig. 15.13: JFileChooserTest.java
2
// Tests class JFileChooserDemo.
3
import
java.io.IOException;
4
import
javax.swing.JFrame;
5
6
public class
JFileChooserTest
7
{
Fig. 15.13
|
Testing class
FileDemonstration
. (Part 1 of 2.)