亲爱的专家们,这个问题与
- 文件在java中不打开,后者位于jar文件中。
更新问题
我用了两个密码
- 打开JAR文件中的pdf文件
如果我从workspace
.
URL resource = Thread.currentThread().getContextClassLoader().getResource("resources/User_Guide.pdf");
File userGuideFile = null;
try {
userGuideFile = new File(resource.getPath());
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
desktop.open(userGuideFile);
}
} catch (Exception e1) {
e1.printStackTrace();
}
但如果我复制我的project.jar到另一个位置,它将不会打开文件,并在我的日志中显示为file is not found "c:\workspace\project...pdf"
。我使用了以下代码同一页我的PdfReaderAdobe阅读器显示异常file is either not supproted or damaged :
代码:
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
InputStream resource = Thread.currentThread().getContextClassLoader().getResource("resources/User_Guide.pdf");
try
{
File file = File.createTempFile("User_Guide", ".pdf");
file.deleteOnExit();
OutputStream out = new FileOutputStream(file);
try
{
// copy contents from resource to out
}
finally
{
out.close();
}
desktop.open(file);
}
finally
{
resource.close();
}
}
注:我试着打开*.txt
文件,它运行良好。但没有在PD
F和DOC
。主要问题是当我运行应用程序更改项目工作空间目录时。实际上我想做的是:Ntebeans键盘-下面的短代码文档Help
菜单
一个罐子是一个压缩档案。所以首先来看看7zip/WinZip之类的。检查其中的路径确实是resources/User_Guide.pdf(大小写敏感!)
很可能是/User_Guide.pdf
在罐子里。
不能立即从资源中获取文件(=文件系统上的文件)(只是偶然)。所以一个人得到了一个InputStream
.
InputStream in = getClass().getResource("/resources/User_Guide.pdf");
NullPointerException
找不到的时候。对于getclass,类必须位于同一个JAR中,在本例中,路径以/
.
现在您可以将输入流复制到某个临时文件中,并打开该文件。在Java 7中:
File file = File.createTempFile("User_Guide", ".pdf");
Files.copy(in, file.toPath());
如果在Files.Copy行中获得FileAlreadyExistsException,则添加以下CopyOption:
Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
对于java<7:
// copy contents from resource to out
byte[] buf = new byte[4096];
while ((int nread = in.read(buf, 0, buf.length)) > 0) {
out.write(buf, 0, nread);
}
下面是博主剪辑的视频资料 可能与文章无关 希望大家可以支持一下哦!谢谢大家支持!
UP主:我只需一小时带你玩转Git&Github B友直呼:菜鸡这不是有手就行?
【面试必备】阿里资深架构师详解 2021最新 Java秒杀系统高性能高并发实战项目
Java零基础小白看完我这个系列视频都可以自己做实战项目啦!拿捏呢!
2021最新版lntellij IDEA 安装、配置、环境变量教学