Java:打开文件(Windows + Mac)

Tje*_*les 6 java pdf file multiplatform

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

我有一个打开文件的java应用程序.这在Windows上运行得很好,但在mac上却不行.

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

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

现在我的问题是在mac中打开它的代码是什么?或者还有另一种方法可以打开可以运行多平台的PDF吗?

编辑:

我创建了如下文件:

File folder = new File("./files");
File[] listOfFiles = folder.listFiles();
Run Code Online (Sandbox Code Playgroud)

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

fileArray.add(listOfFiles[i]);

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

Mar*_*aux 13

这是一个OperatingSystem Detector:

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; };

}
Run Code Online (Sandbox Code Playgroud)

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

回答你的编辑:

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


小智 12

起初,与*.dll相关的任何内容都是windows-ish.

也许您可以尝试下面的Linux代码,它也可能适用于MAC:

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

Desktop d = Desktop.getDesktop();  
d.open(new File("foo.pdf"))
Run Code Online (Sandbox Code Playgroud)