Skip bytes in ByteArray Java

2.1k views Asked by At

My app reads a png-like file (in byte) and stores bytes into a byteArray. This is the method I use :

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;
    }

After that, I want to extract patterns of that byteArray.

It follows the pattern of png file :
4 bytes length + 4 bytes types + data (optional) + CRC and repeats that scheme.

I want to do something like a do while : reading the length + type. If I'm not interested of the type, I want to skip that chunk. But I'm struggling because I can't find any skip method for byteArray[].

Does anyone have an idea of how to proceed ?

2

There are 2 answers

8
ppysz On BEST ANSWER

Have you tried to use ByteArrayInputStream http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html? there is skip method

1
Nagarz On

If you want to iterate through the array with a while and you need to skip to the next iteration on a given condition you can use the label continue to skip to the next iteration of the loop.

The syntax is as follows:

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);