Java:打开文件(Windows + Mac)

可能重复:
如何从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’作为文件夹,路径搞砸了)

这是一个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; }; } 

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

 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()

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

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

 import java.awt.Desktop; import java.io.File; Desktop d = Desktop.getDesktop(); d.open(new File("foo.pdf")) 

你需要查看open命令

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

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

 Runtime.getRuntime().exec(new String[]{"/usr/bin/open", file.getAbsolutePath()});