Reputation: 4149
I want to open a PDF file from a jsp. The jsp and the PDF are in the same directory. I am using the following piece of code:
if (Desktop.isSupported()) {
try {
File myFile = new File("<file name>.pdf");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}
However, I get the error that the file is not found. Verified user.dir and it points to my tomcat/bin. How can I refer to the pdf to open it?
Upvotes: 1
Views: 6091
Reputation: 1108557
You need to specify the absolute file path. Assuming that there's a filename.pdf
in the root of the public webcontent, this should do:
File myFile = new File(getServletContext().getRealPath("/filename.pdf"));
However, this construct won't work the way you'd expect. It will show the PDF file in webserver machine, not in webbrowser machine! Only when you happen to run both the webserver and webbrowser at physically the same machine, this will "work". But this does obviously not happen in real world when you publish your webapp into the internet where the webserver and webbrowser runs at physically different machines.
Instead, you just need to link to the PDF file directly.
<a href="filename.pdf">View PDF</a>
and let the browser handle the display.
Upvotes: 4
Reputation: 2489
Have you tried this? I just got this from google, so I dunno if it will work.
Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler c:\\Java- Interview.pdf");
p.waitFor();
Upvotes: 0