2013-11-21 95 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

相關問題