我想限制我的用户只能访问一个目录及其子目录,但“上级目录”按钮会让他们浏览到任意目录。
我应该怎么做?
我想限制我的用户只能访问一个目录及其子目录,但“上级目录”按钮会让他们浏览到任意目录。
我应该怎么做?
以防万一,如果将来有其他人需要这个:
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);
public TFile getHomeDirectory()
{
return rootDirectories[0];
}
将类和构造函数设置为 public
将 JFileChooser fileChooser = new JFileChooser(fsv);
改为 JFileChooser fileChooser = new JFileChooser(fsv.getHomeDirectory(),fsv);
我使用TrueZips TFileChooser对用户进行限制以保持在zip文件中,并通过对上述代码进行轻微修改,这可以完美地实现。非常感谢。
不需要那么复杂。你可以像这样轻松设置JFileChooser的选择模式
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
你可以在这里阅读更多参考 如何使用文件选择器
getFileSystemView()
。 - McDowell