How do I restrict JFileChooser to a directory?

Incase anyone else needs this in the future:

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;
    }
}

You’ll obviously need to make a better “createNewFolder” method, but this does restrict the user to one of more directories.

And use it like this:

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

or like this:

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

Leave a Comment