Java:打开文件 (Windows + Mac)

标签 java file pdf multiplatform

<分区>

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

关于Java:打开文件 (Windows + Mac),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7024031/

相关文章:

c# - 如何用 C# 替换 PDF 中的文本?

java - 获取 javax.net.ssl.SSLException : Received fatal alert: protocol_version while scraping data using Jsoup

java - 页面上的 Raspberry Pi Tomcat 开关和 LED

linux - Logstash 保持运行而不会崩溃或输出(windows 以及 linux)

python - 使用 urllib2 将大型二进制文件流式传输到文件

delphi - 如何检测流结束?

javascript - 触发 Web 浏览器下载 Blob 响应

php - 标记 PDF 和可选的密码保护

Oracle RAW 的 java 数据类型

java - 如何在我的 Java 代码中实现 ImageJ API?