如何从JFileChooser检索UNC路径而不是映射驱动器路径

只是想知道是否有办法从使用JFileChooser选择的文件返回UNC路径。 我将选择的文件将驻留在具有UNC路径的映射驱动器上。 现在,我似乎只能拉回映射驱动器的驱动器号。

来自https://stackoverflow.com/users/715934/tasoocoo

我最终找到了执行NET USE命令的解决方案:

  filePath = fc.getSelectedFile().getAbsolutePath(); Runtime runTime = Runtime.getRuntime(); Process process = runTime.exec("net use"); InputStream inStream = process.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line = null; String[] components = null; while (null != (line = bufferedReader.readLine())) { components = line.split("\\s+"); if ((components.length > 2) && (components[1].equals(filePath.substring(0, 2)))) { filePath = filePath.replace(components[1], components[2]); } } 

JFileChooser方法getSelectedFile()返回一个File ,它可能包含有用的信息。

“对于Microsoft Windows平台,… UNC路径名的前缀是"\\\\" ;主机名和共享名称是名称序列中的前两个名称。”

如果其他人正在寻找备用(我认为更简单)的解决方案,您可以使用ShellFolder.getDisplayName()找到该信息。 例如,您可以在此处从字符串中解析驱动器的网络位置:

 System.out.println(ShellFolder.getShellFolder(new File(filePath.substring(0,3))).getDisplayName()); 

这可能也很有用:

 File.listRoots(); 

正如我对Gerry的回答所评论的那样, ShellFolder.getDisplayName是不可靠的,因为用户可以将显示名称更改为他们想要的任何名称。

但是,UNC路径似乎可以通过sun.awt.shell.ShellFolder 。 这当然是一个“内部专有API”,所以不能保证这将继续在未来版本的java中工作,但是在Windows 7中针对java 1.8.0_31进行测试我看到一个标题为AttributesShellFolderColumnInfo ,其中网络驱动器似乎包含UNC路径作为一个裸String 。 例如:

 File networkDrive = new File("G:\"); ShellFolder shellFolder = ShellFolder.getShellFolder(networkDrive); ShellFolderColumnInfo[] cols = shellFolder.getFolderColumns(); for (int i = 0; i < cols.length; i++) { if ("Attributes".equals(cols[i].getTitle())) { String uncPath = (String) shellFolder.getFolderColumnValue(i); System.err.println(uncPath); break; // don't need to look at other columns } } 

如果您在资源管理器中转到“我的电脑”,请更改为“详细信息”视图并启用“网络位置”列,它似乎与我们通过ShellFolder API从“属性”获得的内容相匹配。 不确定“属性”来自何处,或者它是否在非英语语言环境中发生变化。