我有一个Directory Lister程序,它只是简单地列出了JTable中的目录/子目录/文件,它以递归方式执行此操作(其中一个要求)。有几个条件必须满足(即检查空目录,检查文件夹/文件是否存在等),测试后一切似乎都很好。 问题是它确实找到了空目录,但是如果我选择打开一个包含空子目录的目录,每次递归找到它时我的对话框都会打开。我发现的是它显示的元数据("。"和#34; ..."文件在我的Linux机器上等于4kb)为空。如果文件夹仅包含那些文件夹,则可以。例如,我的Documents文件夹有" 4kb"数据,但程序说它是空的。
这是整个过程的两种方法:
//this method creates the File object, and calls
//the method containing the recursive function
public void showDirectoryContents(String basePath) {
try {
File file = new File(basePath); //creation of File Object
enumerateDirectory(file); //enumerateDirectory method call
} catch (Exception e) {}
}
//The method for all the required File conditions and recursive function
public void enumerateDirectory(File f) {
File[] theFiles = f.listFiles();
String fileType = ""; //This will display as either a "Folder" or a "File" in the JTable
if(f.isFile())
{
fileType = "File";
gui.updateListing(f.getAbsolutePath(), getSizeString(f.length()), fileType, new Date(f.lastModified()).toString());
}
else if(f.isDirectory())
{
fileType = "Folder";
gui.updateListing(f.getAbsolutePath(), getSizeString(f.length()), fileType, new Date(f.lastModified()).toString());
}
if(f.isDirectory() && f.list().length == 0) {
JOptionPane.showConfirmDialog(gui, "That folder is empty.", "OOPS!", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
gui.setAddressLabelText(""); //clear the Address Label so it doesn't show the directory.
while(gui.tableModel.getRowCount() > 0) {
for(int i = 0; i < gui.tableModel.getRowCount(); i++) {
gui.tableModel.removeRow(i); //remove the empty directory from the JTable before the dialog window pops up.
}
}
}
/*
This code will remove a non-existent folder/file form the Address Label, and remove it from the JTable.
Originally, it was listing it on the label and putting a 0 KB file on the Table
The parameter "gui" in the JOptionPane was created due to the ERROR_MESSAGE popping up on a 2nd monitor if the user has one (the code was tested on dual monitors). This way, it shows up directly in front of the gui.
*/
if(!f.exists()) {
try {
gui.setAddressLabelText("");
int action = JOptionPane.showConfirmDialog(gui, "That file does not exist.", "ERROR", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
if(action == 0) {
while (gui.tableModel.getRowCount() > 0) {
for (int i = 0; i < gui.tableModel.getRowCount(); i++) {
gui.tableModel.removeRow(i);
}
}
}
}catch(NullPointerException e) {
e.getMessage();
}
}
if(f.isDirectory())
{
for(int i = 0; i < theFiles.length; i++) {
enumerateDirectory(theFiles[i]); //recursive function to get all files in specified folder
}
}
}
如果目录包含子目录,如何防止显示对话框?是否存在一种方法(用简单的英语)&#34;如果文件夹包含子文件夹,请继续迭代&#34; ??
我还不熟悉Path类,我还不知道如何使用FileFilter。任何提示/指示将不胜感激。