2014-04-03 160 views
-1

我一直在嘗試從一個內部到外部位置的Java中獲取文件。該文件正在複製,但不傳輸字節。該文件本來是98字節,當傳輸時設置爲0.如果你能告訴我什麼即時通訊做錯了,或以任何方式幫助我,這將是偉大的。Java IO複製文件

private static void copyFile(String internal, File external) { 
    InputStream stream = FileManager.class.getResourceAsStream(internal); 
    if(stream == null) { 
     System.err.println("Error: File not found when trying to copy at location " + internal); 
    } 
    OutputStream resStreamOut = null; 
    int readBytes; 
    byte[] buffer = new byte[4096]; 
    try { 
     resStreamOut = new FileOutputStream(external); 
     while((readBytes = stream.read(buffer)) > 0) { 
      resStreamOut.write(buffer, 0 , readBytes); 
     } 

    } catch(IOException e1) { 
     e1.printStackTrace(); 
     System.exit(1); 
    } finally { 
     try { 
     stream.close(); 
     resStreamOut.close(); 
     } catch(IOException e2) { 
      e2.printStackTrace(); 
      System.exit(1); 
     } 

    } 

} 

編輯:

獲得空指針:

4.4.0 Error: File not found when trying to copy at location /res/shaders/basicFragment.fs 
Exception in thread "main" java.lang.NullPointerException at 
com.thinmatrix.konilax.handlers.FileManager.copyFile(FileManager.java:80) at 
com.thinmatrix.konilax.handlers.FileManager.update(FileManager.java:56) at 
com.thinmatrix.konilax.MainComponent.<init>(MainComponent.java:22) at 
com.thinmatrix.konilax.MainComponent.main(MainComponent.java:115) 
+0

這應該有效。你確定你有正確的輸入嗎?而且你之後並沒有打破輸出?我會在循環中每次跟蹤「readBytes」,以確保你真正到達這裏。 – EJP

+0

您確定您正在使用'FileManager'正確讀取輸入嗎? – deanosaur

+0

林幾乎possitive即時使用FileManager正確使用java的io一段時間這裏是整個類,雖然如果你想檢查。 http://pastebin.com/V0QYv1u2 – user3051391

回答

1

只有當你的代碼管理,以打開讀取文件(測試時注意else語句,如果您的流爲null) :

private static void copyFile(String internal, File external) { 
    InputStream stream = FileManager.class.getResourceAsStream(internal); 
    if(stream == null) { 
     System.err.println("Error: File not found when trying to copy at location " + internal); 
    } else { 
     OutputStream resStreamOut = null; 
     int readBytes; 
     byte[] buffer = new byte[4096]; 
     try { 
      resStreamOut = new FileOutputStream(external); 
      while((readBytes = stream.read(buffer)) > 0) { 
       resStreamOut.write(buffer, 0 , readBytes); 
      } 
     } catch(IOException e1) { 
      e1.printStackTrace(); 
      System.exit(1); 
     } finally { 
      try { 
       stream.close(); 
       resStreamOut.close(); 
      } catch(IOException e2) { 
       e2.printStackTrace(); 
       System.exit(1); 
      } 
     } 
    } 
} 
+0

謝謝你很好的答案,但現在它沒有找到該文件,並且沒有堆棧跟蹤出現,並且暗示爲什麼 – user3051391

+2

@ user3051391「internal」應該是與FileManager類相同的目錄中的文件名(無路徑)(可以是在JAR中分解或壓縮),或者相對於類路徑中的目錄以'/'開始的路徑。 – erickson