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

时间:2011-04-19 20:16:34

标签: java jfilechooser unc

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

4 个答案:

答案 0 :(得分:2)

来自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]);
    }
 }

答案 1 :(得分:1)

JFileChooser方法getSelectedFile()会返回File,其中可能包含有用的信息。

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

答案 2 :(得分:1)

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

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

这可能也很有用:

File.listRoots();

答案 3 :(得分:1)

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

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

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 } } API从“属性”获得的内容相匹配。不确定“属性”的来源或非英语区域设置的变化。