How to open an existing file, for example .docx, .txt, .pptx via java?

I am wondering how to open a file through java.

I can open Office itself this way

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.

+7
java
source share
1 answer

Try it,

  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 using 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 also open pptx files (and more) with this approach.

+8
source share

All Articles