Java:打开文件(Windows + Mac) [英] Java: Open a file (Windows + Mac)
问题描述
我有一个打开文件的java应用程序。这在Windows上完美,但不适用于Mac。
I have a java application that opens a file. This works perfect on windows, but not on mac.
这里的问题是我使用windows配置打开它。代码是:
The problem here is that I use the windows configuration to open it. The code is:
Runtime.getRuntime()。exec(rundll32 url.dll,FileProtocolHandler+ file);
现在我的问题是在mac中打开它的代码是什么?或者是否有其他方法可以打开可以在多平台上运行的PDF?
Now my question is what is the code to open it in mac? Or is there another way to open a PDF that works multi platform?
编辑:
我创建了如下文件:
File folder = new File("./files");
File[] listOfFiles = folder.listFiles();
在循环中我将它们添加到数组中:
in a loop i add them to an array:
fileArray.add(listOfFiles [i]);
如果我尝试打开一个文件那个数组有Desktop.getDesktop()。打开(文件),它说它找不到那个文件(路径搞砸了,因为我用'./files'作为文件夹)
If i try to open a file from that array with Desktop.getDesktop().open(file), it says it can't find that file (the path is messed up because I used './files' as folder)
推荐答案
这是一个OperatingSystem Detector:
Here is an 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; };
}
然后你可以打开这样的文件:
Then you can open files like this:
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;
}
}
回答你的编辑:
Answer to your edit:
尝试使用 file.getAbsoluteFile()
甚至文件.getCanonicalFile()
。
这篇关于Java:打开文件(Windows + Mac)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!