7

我正在创建一个应用程序,在该应用程序中,用户实际上可以很容易地单击应用程序中的链接,该链接会在 Finder(在 Mac 中)/Windows 资源管理器中打开一个特定文件夹。这可能发生在链接或按钮的单击事件上。

有没有办法通过 Swing 打开这些本机操作系统应用程序(针对特定文件夹)?

4

3 回答 3

30

简短的回答:

if (Desktop.isDesktopSupported()) {
    Desktop.getDesktop().open(new File("C:\\"));
}

长答案: 虽然读取它是什么操作系统然后运行特定于操作系统的命令会起作用,但它在一定程度上需要对需要完成的操作进行硬编码。

让 Java 处理每个操作系统应该如何打开目录。不应该让我们头疼。<3 抽象。

阅读#open(File)方法文档表明它将在所有支持该操作的操作系统上打开链接。如果当前平台不支持打开文件夹或文件(比如无头环境?当然,我猜想为什么它不会打开),它会抛出一个UnsupportedOperationException. 如果用户无权读取该文件夹(Windows Vista/7/8,基于 Unix 的机器),您将获得一个SecurityException. 所以如果你问我,它处理得很好。

更新:在获取对象之前添加了一个 if 检查,Desktop以便您的代码免于#getDesktop() Java 文档中提到的讨厌HeadlessException和异常。UnsupportedOperationException

于 2012-09-09T14:59:02.837 回答
10

用于Runtime.getRuntime().exec("command here");在运行 java 的系统中执行命令。

对于 explorer.exe,您可以简单地将文件夹的绝对路径作为参数传递,例如

Explorer.exe "C:\Program Files\Adobe"

在 Mac OS X 中,您可以使用以下open命令:

open /users/

您可以在此处了解如何检测您正在使用的操作系统,以及要运行的代码。例如,如果您在 Windows 上,这将检查:

public static boolean isWindows() {

    String os = System.getProperty("os.name").toLowerCase();
    // windows
    return (os.indexOf("win") >= 0);

}
于 2012-09-09T14:32:47.917 回答
-1

这将从文件系统中获取一个文件:

public static File selectDirectory(JFrame frame, File file, JComponent component, String title) {

    File selectedFile = null;

    if ("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"
            .equalsIgnoreCase(UIManager.getSystemLookAndFeelClassName())) {
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        String absPath = file.getAbsolutePath();
        fc.setSelectedFile(new File(absPath));

        int returnVal = fc.showOpenDialog(component);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            selectedFile = fc.getSelectedFile();
        }
    } else {
        System.setProperty("apple.awt.fileDialogForDirectories", "true");

        FileDialog fd = new FileDialog(frame, title, FileDialog.LOAD);
        String absPath = file.getAbsolutePath();
        fd.setDirectory(absPath);
        fd.setFile(absPath);

        fd.setVisible(true);

        if (fd.getFile() != null) {
            String selectedFileName = fd.getDirectory() + File.separator + fd.getFile();
            selectedFile = new File(selectedFileName);
        }
    }

    return selectedFile;
}
于 2018-05-24T16:00:30.720 回答