包中的文件不会从java应用程序中打开。

亲爱的专家们,这个问题与

  • 文件在java中不打开,后者位于jar文件中。

更新问题

我用了两个密码

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文件,它运行良好。但没有在PDF和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 安装、配置、环境变量教学

2021最新算法训练营:左神带你 爆刷LeetCode算法(1000题) 进大厂的必修算法课程!

B站首发 花费12980巨资购买的 微服务SpringCloud Alibaba全集

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java盘鱼宴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值