如何通过java打开像.docx,.txt,.pptx这样的现有文件?

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

我可以像这样打开Office

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

但我想直接从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(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 } } 

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