我正在尝试使用以下代码将图像文件从资源文件夹复制到本地系统。
InputStream inStream = null;
OutputStream outStream = null;
File bfile = new File(directoryPath + "/icons/" + outputFileName);
inStream = MyClass.class.getClassLoader().getResourceAsStream("/images/" + imgFileName);
try {
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
if (inStream != null && outStream != null) {
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
}
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}
当我运行eclipse时,这段代码非常正常。但是当我构建产品时,图标不会被复制到本地系统。
我也试过
inStream = MyClass.class.getResourceAsStream("/images/" + imgFileName);
但没有运气。
有任何想法!
答案 0 :(得分:0)
要打开输入流,请考虑使用FileLocator API:
FileInputStream is = null;
FileOutputStream fo = null;
FileChannel inputChannel = null;
FileChannel outputChannel = null;
File bfile = new File(directoryPath + "/icons/" + outputFileName);
try {
is = FileLocator.openStream(Activator.getDefault().getBundle(), new Path("/images/" + imgFileName), false);
inputChannel = is.getChannel();
fo = new FileOutputStream(bfile);
outputChannel = fo.getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
// close everything in finally
}
另请注意,最好关闭finally
块