是否有一种与平台无关的方式使用Java来检测文件所在的驱动器类型?基本上我有兴趣区分:硬盘,可移动驱动器(如USB记忆棒)和网络共享。 JNI / JNA解决方案没有帮助。可以假设Java 7。
答案 0 :(得分:4)
Swing的FileSystemView
类具有部分功能,以支持检测驱动器的类型(参见isFloppyDrive
,isComputerNode
)。我担心没有标准的方法来检测驱动器是否通过USB连接。
未经考验的未经考验的例子:
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
....
JFileChooser fc = new JFileChooser();
FileSystemView fsv = fc.getFileSystemView();
if (fsv.isFloppyDrive(new File("A:"))) // is A: a floppy drive?
在JDK 7中还有另一种选择。我没有使用它,但FileStore
API有一个type
方法。 documentation说:
此方法返回的字符串格式具有高度特定于实现的格式。例如,它可能表示使用的格式或文件存储是本地还是远程。
显然,使用它的方式是:
import java.nio.*;
....
for (FileStore store: FileSystems.getDefault().getFileStores()) {
System.out.printf("%s: %s%n", store.name(), store.type());
}
答案 1 :(得分:4)
您可以使用Java执行cmd:
fsutil fsinfo drivetype {drive letter}
结果会给你这样的东西:
C: - Fixed Drive
D: - CD-ROM Drive
E: - Removable Drive
P: - Remote/Network Drive
答案 2 :(得分:0)
特别注意http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/filechooser/FileSystemView.html
我个人没有用过这个,但似乎有用。它有像isFloppyDrive
这样的方法。
另请查看JSmooth
答案 3 :(得分:0)
这是一个Gist,它显示了如何使用net use
来确定这一点:https://gist.github.com/digulla/31eed31c7ead29ffc7a30aaf87131def
代码中最重要的部分:
public boolean isDangerous(File file) {
if (!IS_WINDOWS) {
return false;
}
// Make sure the file is absolute
file = file.getAbsoluteFile();
String path = file.getPath();
// System.out.println("Checking [" + path + "]");
// UNC paths are dangerous
if (path.startsWith("//")
|| path.startsWith("\\\\")) {
// We might want to check for \\localhost or \\127.0.0.1 which would be OK, too
return true;
}
String driveLetter = path.substring(0, 1);
String colon = path.substring(1, 2);
if (!":".equals(colon)) {
throw new IllegalArgumentException("Expected 'X:': " + path);
}
return isNetworkDrive(driveLetter);
}
/** Use the command <code>net</code> to determine what this drive is.
* <code>net use</code> will return an error for anything which isn't a share.
*
* <p>Another option would be <code>fsinfo</code> but my gut feeling is that
* <code>net</code> should be available and on the path on every installation
* of Windows.
*/
private boolean isNetworkDrive(String driveLetter) {
List<String> cmd = Arrays.asList("cmd", "/c", "net", "use", driveLetter + ":");
try {
Process p = new ProcessBuilder(cmd)
.redirectErrorStream(true)
.start();
p.getOutputStream().close();
StringBuilder consoleOutput = new StringBuilder();
String line;
try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
while ((line = in.readLine()) != null) {
consoleOutput.append(line).append("\r\n");
}
}
int rc = p.waitFor();
// System.out.println(consoleOutput);
// System.out.println("rc=" + rc);
return rc == 0;
} catch(Exception e) {
throw new IllegalStateException("Unable to run 'net use' on " + driveLetter, e);
}
}