2015-06-15 22 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