如何通过java打开.docx、.txt、.pptx等现有文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20494773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:20:11  来源:igfitidea点击:

how to open existing file like .docx, .txt, .pptx through java?

java

提问by Kashama Shinn

I am wondering how to open a file through java.

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

I can open Office itself like this

我可以像这样打开 Office 本身

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

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

But I want to open files directly from java.

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

采纳答案by sikander

Try this,

尝试这个,

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

or you can do it this with Desktop.open(File),

或者你可以这样做Desktop.open(File)

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

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

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