java打开pdf文件,如何从Java打开pdf文件?

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(".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?

解决方案

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.

View PDF

and let the browser handle the display.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值