2015-06-15 70 views
1

我的應用程序讀取類似png的文件(以字節爲單位)並將字節存儲到byteArray中。 這是我使用的方法:在ByteArray中跳過字節Java

public static byte[] read(File file) throws IOException { 

     byte []buffer = new byte[(int) file.length()]; 
     InputStream ios = null; 
     try { 
      ios = new FileInputStream(file); 
      if (ios.read(buffer) == -1) { 
       throw new IOException("EOF reached while trying to read the whole file"); 
      }   
     } finally { 
      try { 
       if (ios != null) 
         ios.close(); 
      } catch (IOException e) { 
      } 
     } 

     return buffer; 
    } 

在那之後,我想提取字節組的模式。

它遵循PNG文件的圖案:
4字節長度+ 4種字節類型+數據(可選)+ CRC並重復該方案。

我要像做一做,同時:讀取長度+型。如果我對這種類型不感興趣,我想跳過這個塊。 但我很掙扎,因爲我找不到任何跳過方法 byteArray []。

有誰有如何進行的想法?

回答

2

您是否嘗試過使用ByteArrayInputStream的http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html?有跳過方法

+0

我之前看到過這個類。但我不知道如何使用它。我是否必須將我的FileInputStream替換爲ByteArrayInputStream? – tmylamoule

+0

如果FileInputStream中沒有任何重要的東西可以替換它,它們都具有相同的父類。這是你的足夠的例子http://www.tutorialspoint.com/java/io/bytearrayinputstream_skip.htm? – Czarny

+0

是的,謝謝你的幫助。我在做這個工作。會給你一個反饋! ;) – tmylamoule

0

如果你想通過while數組進行迭代,你需要跳到下一個迭代在給定的條件下,你可以使用標籤繼續跳到循環的下一次迭代。

的語法如下:

do { 
    if (condition) { 
     continue; 
    } 
    // more code here that will only run if the condition is false 
} while(whatever you use to iterate over your array); 
+0

這是我的想法。但我不知道如何填補白色的爭論。 目前,我做了一個「for循環」,每字節增加字節數並搜索4字節的TYPE。但是這個循環非常慢:20Mb文件需要7秒。 (我有250Mb的文件可讀) – tmylamoule