6

可能重复:
如何从 Java 启动给定文件的默认(本机)应用程序?

我有一个打开文件的 java 应用程序。这在 Windows 上非常有效,但在 mac 上却不行。

这里的问题是我使用windows配置打开它。代码是:

Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + file);

现在我的问题是在mac中打开它的代码是什么?还是有另一种方法可以打开适用于多平台的 PDF?

编辑:

我创建的文件如下:

File folder = new File("./files");
File[] listOfFiles = folder.listFiles();

在一个循环中,我将它们添加到一个数组中:

fileArray.add(listOfFiles[i]);

如果我尝试使用 Desktop.getDesktop().open(file) 从该数组中打开一个文件,它会说找不到该文件(路径混乱,因为我使用 './files' 作为文件夹)

4

3 回答 3

14

这是一个操作系统检测器:

public class OSDetector
{
    private static boolean isWindows = false;
    private static boolean isLinux = false;
    private static boolean isMac = false;

    static
    {
        String os = System.getProperty("os.name").toLowerCase();
        isWindows = os.contains("win");
        isLinux = os.contains("nux") || os.contains("nix");
        isMac = os.contains("mac");
    }

    public static boolean isWindows() { return isWindows; }
    public static boolean isLinux() { return isLinux; }
    public static boolean isMac() { return isMac; };

}

然后你可以像这样打开文件:

public static boolean open(File file)
{
    try
    {
        if (OSDetector.isWindows())
        {
            Runtime.getRuntime().exec(new String[]
            {"rundll32", "url.dll,FileProtocolHandler",
             file.getAbsolutePath()});
            return true;
        } else if (OSDetector.isLinux() || OSDetector.isMac())
        {
            Runtime.getRuntime().exec(new String[]{"/usr/bin/open",
                                                   file.getAbsolutePath()});
            return true;
        } else
        {
            // Unknown OS, try with desktop
            if (Desktop.isDesktopSupported())
            {
                Desktop.getDesktop().open(file);
                return true;
            }
            else
            {
                return false;
            }
        }
    } catch (Exception e)
    {
        e.printStackTrace(System.err);
        return false;
    }
}

回答您的编辑:

尝试使用file.getAbsoluteFile()甚至file.getCanonicalFile().

于 2011-08-11T10:42:51.540 回答
13

起初,与 *.dll 相关的任何东西都是 Windows 风格的。

也许你可以试试下面的 Linux 代码,它也可以在 MAC 上工作:

import java.awt.Desktop;
import java.io.File;

Desktop d = Desktop.getDesktop();  
d.open(new File("foo.pdf"))
于 2011-08-11T10:08:59.333 回答
3

你需要看看命令打开所以有

Runtime.getRuntime().exec("/usr/bin/open " + file);

Martijn 编辑
这更好,当您在文件路径中使用空格时:

Runtime.getRuntime().exec(new String[]{"/usr/bin/open", file.getAbsolutePath()});
于 2011-08-11T10:08:17.707 回答