2016-02-09 40 views
-3

我對Java很陌生,最近我正在製作一個程序,它從一個目錄讀取圖像文件(jpg),並將它們寫入(複製)到另一個目錄。用Java在本地文件系統之間無imageio讀寫圖像

我無法使用imageio或移動/複製方法,而且我還必須檢查由R/W操作導致的耗時。

問題是我在下面寫了一些代碼,它運行,但目標中的所有輸出圖像文件都有0字節,根本沒有內容。 當我打開結果圖像時,我只能看到沒有字節的黑色屏幕。

public class image_io { 

public static void main(String[] args) 
{ 
    FileInputStream fis = null; 
    FileOutputStream fos = null; 
    BufferedInputStream bis = null; 
    BufferedOutputStream bos = null; 

    // getting path 
    File directory = new File("C:\\src"); 
    File[] fList = directory.listFiles(); 
    String fileName, filePath, destPath; 

    // date for time check 
    Date d = new Date(); 

    int byt = 0; 
    long start_t, end_t; 

    for (File file : fList) 
    { 
     // making paths of source and destination 
     fileName = file.getName(); 
     filePath = "C:\\src\\" + fileName; 
     destPath = "C:\\dest\\" + fileName; 

     // read the images and check reading time consuming 
     try 
     { 
     fis = new FileInputStream(filePath); 
     bis = new BufferedInputStream(fis); 

     do 
     { 
      start_t = d.getTime(); 
     } 
     while ((byt = bis.read()) != -1); 

     end_t = d.getTime(); 
     System.out.println(end_t - start_t); 

     } catch (Exception e) {e.printStackTrace();} 

     // write the images and check writing time consuming 
     try 
     { 
      fos = new FileOutputStream(destPath); 
      bos = new BufferedOutputStream(fos); 

      int idx = byt; 

      start_t = d.getTime(); 

      for (; idx == 0; idx--) 
      { 
       bos.write(byt); 
      } 

      end_t = d.getTime(); 
      System.out.println(end_t - start_t); 

     } catch (Exception e) {e.printStackTrace();} 
    } 
} 

}

是的FileInput/OutputStream中不支持的圖像文件? 或者在我的代碼中有一些錯誤?

請,有人幫助我..

+0

您可能想檢查一下,即使您可能不會使用Apache方法(我認爲第一種方法最適合您的需要):http://examples.javacodegeeks。COM /核心的Java/IO /文件/ 4路到複製文件中的Java / – T145

回答

0

有多個問題與您的代碼:

有了這個循環

do 
{ 
    start_t = d.getTime(); 
} 
while ((byt = bis.read()) != -1); 

你試圖讀取該文件。問題在於,你總是隻記住一個字節並將其存儲到byt。在下一次迭代中,它會被文件中的下一個字節覆蓋,直到達到結尾,在這種情況下,讀取值爲-1。所以這個循環的淨效果是byt等於-1。您需要將所有字節讀取到某個緩衝區,例如一個足夠容納整個文件的數組。

此處的另一個問題是您重複設置start_t。進入循環之前,您可能只需要執行一次此操作。還要注意,d.getTime()將始終返回相同的值,即您在執行Date d = new Date();時得到的值。你可能想打電話System.currentTimeMillis()或類似的東西。

解決了上述問題後,需要相應地調整寫入循環。

你也應該考慮一些Java編碼指南,爲你的代碼侵犯了幾種常見的做法:類和變量

  • 命名風格(image_io =>ImageIOstart_t =>startTime ...)
  • 宣言(例如您的流和idx
  • 某些縮進問題(例如,第一次嘗試的塊沒有縮進)
  • 你不關閉你的流。如果你有Java 7+可用,你應該看看try-with-resources,它會自動關閉你的流。

當你的程序做你想做的事情時,你可以在Code Review上發佈它,以獲得關於你可以改進的東西的額外建議。

相關問題