如何将JFileChooser限制在一个目录中?

26

我想限制我的用户只能访问一个目录及其子目录,但“上级目录”按钮会让他们浏览到任意目录。

我应该怎么做?

4个回答

22

以防万一,如果将来有其他人需要这个:

class DirectoryRestrictedFileSystemView extends FileSystemView
{
    private final File[] rootDirectories;

    DirectoryRestrictedFileSystemView(File rootDirectory)
    {
        this.rootDirectories = new File[] {rootDirectory};
    }

    DirectoryRestrictedFileSystemView(File[] rootDirectories)
    {
        this.rootDirectories = rootDirectories;
    }

    @Override
    public File createNewFolder(File containingDir) throws IOException
    {       
        throw new UnsupportedOperationException("Unable to create directory");
    }

    @Override
    public File[] getRoots()
    {
        return rootDirectories;
    }

    @Override
    public boolean isRoot(File file)
    {
        for (File root : rootDirectories) {
            if (root.equals(file)) {
                return true;
            }
        }
        return false;
    }
}

显然你需要编写一个更好的 "createNewFolder" 方法,但这将限制用户只能使用一个或多个目录。

使用方法如下:

FileSystemView fsv = new DirectoryRestrictedFileSystemView(new File("X:\\"));
JFileChooser fileChooser = new JFileChooser(fsv);

或者像这样:

FileSystemView fsv = new DirectoryRestrictedFileSystemView( new File[] {
    new File("X:\\"),
    new File("Y:\\")
});
JFileChooser fileChooser = new JFileChooser(fsv);

14

你如何获取默认的FileSystemView(例如委托给它)? - Jason S
1
@Jason S - 可能通过静态方法 getFileSystemView() - McDowell
2
如果有人需要,这里是 OP 所需的确切示例: http://tips4java.wordpress.com/2009/01/28/single-root-file-chooser/ - Big_Chair

5
Allain的解决方案几乎完成,还有三个问题需要解决:
  1. 点击“主页”按钮会将用户踢出限制
  2. DirectoryRestrictedFileSystemView在包外无法访问
  3. 起点不是根目录

  1. 在DirectoryRestrictedFileSystemView中添加 @Override

public TFile getHomeDirectory() { return rootDirectories[0]; }

  1. 将类和构造函数设置为 public

  2. JFileChooser fileChooser = new JFileChooser(fsv); 改为 JFileChooser fileChooser = new JFileChooser(fsv.getHomeDirectory(),fsv);

我使用TrueZips TFileChooser对用户进行限制以保持在zip文件中,并通过对上述代码进行轻微修改,这可以完美地实现。非常感谢。


-2

不需要那么复杂。你可以像这样轻松设置JFileChooser的选择模式

JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);

你可以在这里阅读更多参考 如何使用文件选择器


3
这限制了它们只能在一般目录中搜索,而不能指定特定目录,这是原帖提出的问题。 - james.garriss

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接