JFileChooser.FILES_ONLY 获取文件和目录

JFileChooser.FILES_ONLY getting both files and directories

我正在尝试使用 JFileChooser 仅 select 文件删除文件夹中的任何目录:

fc.setFileSelectionMode(JFileChooser.FILES_ONLY);               // Only look at files
fc.setCurrentDirectory(new File(dbPath));
int returnVal = fc.showOpenDialog(null);                        // Switch DB dialog
if (returnVal == JFileChooser.APPROVE_OPTION)                   // Get good DB?
{

    filePDF = fc.getSelectedFile().getAbsolutePath();       // Get path
    txtTSDir.setText(filePDF);
}
else

但是,我得到了文件和目录。这看起来很简单。我错过了什么?

抱歉不得不重写它,有时我在解释的时候脑子里乱七八糟。

好的,所以您认为将 FileSelectionMode 设置为 FILES_ONLY 将使您的 JFileChooser 仅显示文件而不再显示目录。 但实际发生的是它不再让你 select 一个目录作为输入。 这是为了确保您按预期获得文件。

但是。 由于在没有看到目录的情况下导航会非常不方便,它们仍然会显示出来,您可以进入它们(当然)

同样适用于 direcotries_only 这仍然会向您显示文件,但您不能 select 它们作为输入。

JFileChooser.FILES_ONLY 标志表示您只能 select 个文件。显示目录是因为用户可能想在其中查找文件。

如果您想从视图中排除目录,请使用 FileFilter

fc.setFileFilter(new FileFilter() {

        @Override
        public String getDescription() {
            return "Only files";
        }

        @Override
        public boolean accept(File f) {
            return !f.isDirectory();
        }
    });

您似乎想隐藏目录。所以,只需创建自定义 FileSystemView:

JFileChooser jFileChooser = new JFileChooser();

jFileChooser.setFileSystemView(new FileSystemView() {
    @Override
    public File[] getFiles(File dir, boolean useFileHiding) {
        return Arrays.stream(super.getFiles(dir, useFileHiding)).filter(File::isFile).toArray(File[]::new);
    }

    @Override
    public File createNewFolder(File containingDir) throws IOException {
        throw new NotImplementedException();
    }
});

如您所见,我在 getFiles 方法中只留下文件,现在我只看到我的主目录中的文件: