2013-11-21 135 views
0

我试图使用以下代码将映像文件从资源文件夹复制到本地系统。getResourceAsStream()在构建产品中不工作

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

为了打开一个输入流考虑使用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

相关问题