在Netbeans IDE外部运行时,文件无法正确读取/创建

时间:2013-09-27 07:14:51

标签: java file file-io inputstream outputstream

我搜索并找到了很多答案,我试过了。以下是其中之一:

if (Desktop.isDesktopSupported()) {
        try {
            InputStream is = getClass().getResourceAsStream("/folder/SMSCApplication.pdf");
            System.out.println("reading file path ");
            byte[] data = new byte[is.available()];
            is.read(data);
            is.close();
            String tempFile = "User_Guide";
            File temp = File.createTempFile(tempFile, ".pdf");
            FileOutputStream fos = new FileOutputStream(temp);
            fos.write(data);
            fos.flush();
            fos.close();
            Desktop.getDesktop().open(temp);
        } catch (IOException ex) {
            ex.printStackTrace();
            System.out.println("NO PDF READER INSTALLED");
        }
    }

我使用Netbeans IDE运行应用程序它工作正常。但是,当我在Netbeans外面跑步时,它无法工作。文件在temp文件夹上创建但已损坏(当我尝试使用我的默认pdf阅读器时打开)。

我的问题是,"如果我在netbeans之外运行应用程序表单,如何使内部netbeans可行?"吗

注意:我的pdf文件位于package内,因为如果我分发我的应用,则无需单独提供user_guide个文件

更新

file directory

2 个答案:

答案 0 :(得分:0)

您的文件路径错误。

您应该检查InputStream是否为空。

if(is == null) System.out.println("Couldn't open");

使用完全限定的路径。

答案 1 :(得分:0)

感谢大家的支持。最后我找到了HERE的解决方案。我使用了第三方Commons IO库并将代码byte[] data = new byte(iss.available());更改为byte[] data = IOUtils.toByteArray(iss); 并且工作。感谢andy

try {
        InputStream iss = getClass().getResourceAsStream("/folder/SMSCApplication.pdf"); //update the filename here when the help guide is written
        byte[] data = IOUtils.toByteArray(iss);
        iss.read(data);
        iss.close();
        String tempFile = "User_Guide";
        File temp = File.createTempFile(tempFile, ".pdf");
        FileOutputStream fos = new FileOutputStream(temp);
        fos.write(data);
        fos.flush();
        fos.close();
        logger.error(temp.getAbsolutePath());
        Desktop.getDesktop().open(temp.getAbsoluteFile());
    } catch (IOException ex) {
        logger.error(ex);

    }