Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

I am wondering how to open a file through java.

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

But I want to open files directly from java.

like image 792
Kashama Shinn Avatar asked Dec 10 '13 12:12

Kashama Shinn


1 Answers

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

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.

like image 60
Sikander Avatar answered Sep 20 '22 05:09

Sikander