文件没有在jar文件里面的java中打开

时间:2013-09-25 16:10:51

标签: java file-io fileinputstream fileoutputstream

我试图从我的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 个答案:

答案 0 :(得分:1)

getDesktop#open仅允许从文件系统打开文件。一种解决方案是将PDF文件保存在文件系统本地并从那里读取。这消除了从JAR本身提取文件,因此效率更高。

答案 1 :(得分:1)

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

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

祝你好运!

答案 2 :(得分:1)

假设test.pdf在包文件中,请尝试:

File myFile = new File(getClass().getResource("/files/test.pdf").toURI());

答案 3 :(得分:0)

此代码工作正常请使用此命令在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) {}