Java:打开文件(Windows + Mac)

我有一个打开文件的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()

以上是 Java:打开文件(Windows + Mac) 的全部内容, 来源链接: utcz.com/qa/406561.html

回到顶部