Possible Duplicate:
How to launch the default (native) application for a given file from 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”作为文件夹)
这是一个操作系统检测器:
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()
。