有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

文件未在jar文件中的java中打开

我试图从java应用程序中打开文件。使用来自的以下代码

Open PDF file on fly from Java application

代码:

if (Desktop.isDesktopSupported()) {
    try {
        File myFile = new File("/path/to/file.pdf");
        Desktop.getDesktop().open(myFile);
    } catch (IOException ex) {
    // no application registered for PDFs
    }
}

当我使用如下路径时:

"C:\\Users\\kalathoki\\Documents\\NetBeansProjects\\TestJava\\src\\files\\test.pdf" 

它打开了。但是我的文件在我的包里

files/test.pdf 

我曾经

files\\test.pdf 

它显示以下异常:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: \files\test.pdf doesn't exist.

为什么??任何想法。。。我想在jar文件中包含我的文件,用户需要时可以从我的应用程序打开该文件

谢谢


共 (4) 个答案

  1. # 1 楼答案

    这段代码运行正常,请使用它打开jar文件中的pdf文件

        try {
            // TODO add your handling code here:
            String path = jTextField1.getText();
            System.out.println(path);
            Path tempOutput = null;
            String tempFile = "myFile";
            tempOutput = Files.createTempFile(tempFile, ".pdf");
            tempOutput.toFile().deleteOnExit();
            InputStream is = getClass().getResourceAsStream("/JCADG.pdf");
            Files.copy(is,tempOutput,StandardCopyOption.REPLACE_EXISTING);
            if(Desktop.isDesktopSupported())
            {
                Desktop dTop = Desktop.getDesktop();
                if(dTop.isSupported(Desktop.Action.OPEN))
                {
                    dTop.open(tempOutput.toFile());
                }
            }
        } catch (IOException ex) {}
    
  2. # 2 楼答案

    假设测试。pdf在程序包文件中,请尝试以下操作:

    File myFile = new File(getClass().getResource("/files/test.pdf").toURI());
    
  3. # 3 楼答案

    ^{}只允许从文件系统打开文件。一种解决方案是将PDF文件本地保存在文件系统中,并从那里读取。这消除了从JAR本身提取文件的过程,因此效率更高

  4. # 4 楼答案

    不幸的是,您无法通过jar中包含的桌面加载文件

    然而,你并不是没有选择。一个很好的解决方法是创建一个临时文件,然后按detailed here打开它

    祝你好运