请问是否有一种方法可以从使用JFileChooser选择的文件返回UNC路径。我将选择的文件位于具有UNC路径的映射驱动器上。目前,我只能获取到映射驱动器的驱动器字母。
请问是否有一种方法可以从使用JFileChooser选择的文件返回UNC路径。我将选择的文件位于具有UNC路径的映射驱动器上。目前,我只能获取到映射驱动器的驱动器字母。
我最终找到了一种解决方案,执行NET USE命令:
注:https://stackoverflow.com/users/715934/tasoocoo
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]);
}
}
ShellFolder.getDisplayName
不可靠,因为用户可以将显示名称更改为任何他们想要的内容。sun.awt.shell.ShellFolder
获得。当然,这是一个“内部专有 API”,因此不能保证它在未来版本的 Java 中仍能正常工作,但在 Windows 7 中针对 java 1.8.0_31 进行测试时,我看到一个名为 Attributes
的 ShellFolderColumnInfo
,对于网络驱动器,它似乎包含 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获取的“属性”相匹配。不确定“属性”来自何处或在非英语环境中是否会更改。IShellDetails :: getDetailsOf
来填充ShellFolderColumnInfo.title
,根据此处所述,它可以根据语言环境进行更改:https://msdn.microsoft.com/en-us/library/windows/desktop/bb775104%28v=vs.85%29.aspx但是MSDN还说列0/1/2/3始终是名称/大小/类型/修改日期。Java的ColumnInfo标题与MSDN匹配,但实际上列值表示DiskLabel / Type / Size / FreeSpace。直接索引列可能更具可移植性,例如String uncPath =(String)shellFolder.getFolderColumnValue(6);
- sqweekJFileChooser
方法 getSelectedFile()
返回一个 File
,其中可能包含有用的信息。
"对于 Microsoft Windows 平台,UNC 路径名的前缀是 "\\\\"
;主机名和共享名是名称序列中的前两个名称。"
如果其他人正在寻找另一种(并且我认为更简单)的解决方案, 您可以使用ShellFolder.getDisplayName()获取信息。例如,您可以从此处的字符串中解析驱动器的网络位置:
System.out.println(ShellFolder.getShellFolder(new File(filePath.substring(0,3))).getDisplayName());
这也可能会有用:
File.listRoots();
$SHARENAME (\\$SERVER)
的内容。但是用户可以自由更改此标签为完全不同的内容,因此依赖于ShellFolder.getDisplayName
始终具有此信息是不明智的。 - sqweek
JFileChooser
方法getSelectedFile()
返回一个包含此信息的File
。 - trashgod