问题
我有一个JFileChooser,需要以编程方式将其currentDirectory设置为包含多个SMB共享的网络主机(例如\\blah
)。从技术上讲,这不是一个“目录”,而是代表可用共享列表的shell文件夹。
JFileChooser可以轻松导航到特定共享(例如
\\blah\someShare
),但无法处理主机“目录”本身(例如\\blah
)。用户可以通过经过“网络”shell文件夹或查找特定共享并导航到其父目录来在JFileChooser中导航到此类“目录”。调试显示,在幕后,此目录表示为
Win32ShellFolder2
。到目前为止,我所有尝试的编程设置currentDirectory都失败了。new File("\\\\blah")
可以创建,但是Java无法确定其实际是否存在。
尝试失败的解决方案
chooser.setCurrentDirectory(new File("\\\\blah"));
失败,因为
JFileChooser
检查给定的目录是否存在,而new File("\\\\blah").exists()
返回false。File dir = new File("\\\\blah").getCanonicalFile();
失败并引发异常:
java.io.IOException: Invalid argument
at java.io.WinNTFileSystem.canonicalize0(Native Method)
at java.io.WinNTFileSystem.canonicalize(WinNTFileSystem.java:428)
at java.io.File.getCanonicalPath(File.java:618)
at java.io.File.getCanonicalFile(File.java:643)
File dir = ShellFolder.getShellFolder(new File("\\\\blah"));
执行时会抛出异常:
java.io.FileNotFoundException
at sun.awt.shell.ShellFolder.getShellFolder(ShellFolder.java:247)
File dir = new Win32ShellFolderManager2().createShellFolder(new File("\\\\blah"));
执行时抛出了异常:
java.io.FileNotFoundException: File \\blah not found
at sun.awt.shell.Win32ShellFolderManager2.createShellFolder(Win32ShellFolderManager2.java:80)
at sun.awt.shell.Win32ShellFolderManager2.createShellFolder(Win32ShellFolderManager2.java:64)
Path dir = Paths.get("\\\\blah");
会抛出一个异常:
java.nio.file.InvalidPathException: UNC path is missing sharename: \\blah
at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:118)
at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
at java.nio.file.Paths.get(Paths.java:84)