[英]File is not reading/creating properly when running outside Netbeans IDE
I searched and found many answer and I tried. 我搜索并找到许多答案,然后尝试了。 Following is one of them:
以下是其中之一:
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");
}
}
I run application with Netbeans IDE it is working fine. 我使用Netbeans IDE运行应用程序,它运行正常。 But when I run outside Netbeans it is not working.
但是,当我在Netbeans之外运行时,它不起作用。 File creates on
temp
folder but corrupted ( When I try to open using my default pdf
reader ). 文件在
temp
文件夹上创建,但已损坏( 当我尝试使用默认的pdf
阅读器打开时 )。
My question is, "how to make workable like inside netbeans if I run application form outside netbeans also" ? 我的问题是,“如果我也在netbeans之外运行应用程序表单,如何使它像netbeans一样可行”?
Note : My pdf
file is inside package
because if I distribute my application no need to give user_guide
file seperately 注意:我的
pdf
文件位于package
因为如果我分发应用程序,则无需单独提供user_guide
文件
Updated: 更新:
You have your filepath wrong. 您的文件路径错误。
You should be checking if InputStream is null. 您应该检查InputStream是否为null。
if(is == null) System.out.println("Couldn't open");
Use Fully qualified paths. 使用完全限定的路径。
Thanks to all for your support. 感谢大家的支持。 Finally I found the solution from HERE .
最后,我从这里找到了解决方案。 I used third party Commons IO library and changed code
byte[] data = new byte(iss.available());
我使用了第三方Commons IO库,并更改了代码
byte[] data = new byte(iss.available());
to byte[] data = IOUtils.toByteArray(iss);
到
byte[] data = IOUtils.toByteArray(iss);
and worked. 和工作。 Thanks to 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.