如何通过java打开像.docx,.txt,.pptx这样的现有文件? [英] how to open existing file like .docx, .txt, .pptx through java?

查看:97
本文介绍了如何通过java打开像.docx,.txt,.pptx这样的现有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何通过java打开文件。

I am wondering how to open a file through java.

我可以像这样打开Office本身

I can open Office itself like this

     try {
        Runtime runTime = Runtime.getRuntime();
        Process process = runTime.exec("C:\\Program Files\\Microsoft Office\\Office15\\EXCEL.EXE");

    } catch (IOException e) {
        e.printStackTrace();
    }

但我想直接从java打开文件。

But I want to open files directly from java.

推荐答案

试试这个,

    try{

        if ((new File("c:\\your_file.pdf")).exists()) {

            Process p = Runtime
               .getRuntime()
               .exec("rundll32 url.dll,FileProtocolHandler c:\\your_file.pdf");
            p.waitFor();

        } else {

            System.out.println("File does not exist");

        }

      } catch (Exception ex) {
        ex.printStackTrace();
      }

或者你可以用 Desktop.open来做到这一点(文件)

if (Desktop.isDesktopSupported()) {
    try {
        File myFile = new File("/path/to/file.pdf");
        Desktop.getDesktop().open(myFile);
    } catch (IOException ex) {
        // no application registered for PDFs
    }
}

您可以使用此方法打开pptx(及更多)文件。

You can open pptx (and more) files as well with this approach.

这篇关于如何通过java打开像.docx,.txt,.pptx这样的现有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆