Just wondering if there is a way to return back the UNC path from a file chosen with JFileChooser. The file that I would be selecting would reside on a mapped drive that has a UNC path. Right now, I can only seem to pull back the drive letter of a mapped drive.
问题:
回答1:
From https://stackoverflow.com/users/715934/tasoocoo
I ended up finding a solution that executes the NET USE command:
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]);
}
}
回答2:
If anyone else is looking for an alternate (and I think simpler) solution, you can find the information using ShellFolder.getDisplayName(). For example, you can parse the network location of the drive from the string here:
System.out.println(ShellFolder.getShellFolder(new File(filePath.substring(0,3))).getDisplayName());
This might also be useful:
File.listRoots();
回答3:
As I commented on Gerry's answer, ShellFolder.getDisplayName
is unreliable because the user can changed the display name to whatever they want.
However the UNC path does seem to be available via sun.awt.shell.ShellFolder
. This is of course an "internal proprietary API" so no guarantee this will continue to work in future versions of java, but testing against java 1.8.0_31 in Windows 7 I see a ShellFolderColumnInfo
titled Attributes
which for network drives appears to include the UNC path as a bare String
. eg:
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
}
}
If you go to My Computer in explorer, change to Details view and turn on the "Network Location" column, it appears to match what we get from "Attributes" via the ShellFolder
API. Not sure where "Attributes" comes from or if it changes in non-english locales.
回答4:
The JFileChooser
method getSelectedFile()
returns a File
, which may have helpful information.
"For Microsoft Windows platforms,…the prefix of a UNC pathname is "\\\\"
; the hostname and the share name are the first two names in the name sequence."