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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With