0

I have a below snippet which works perfectly in Grrovy, now am trying to convert it to java but am getting

protected String[] extractText(byte[] fileData) {
    //Remove the BOM if present
    if (fileData.length > 3 && fileData[0..2] == [0xEF, 0xBB, 0xBF] as byte[])
    {
      fileData = fileData[3..fileData.length-1]
    }
   // method implemaentation
}

I tried changing it as below but am getting Incompatible operand types byte and byte[] compiler error

 byte[] array= { (byte)0xEF, (byte)0xBB, (byte)0xBF };
fileData.length > 3 && fileData[0..2] == array

I've never worked with byte arrays, Could anyone please help me with this?

OTUser
  • 3,788
  • 19
  • 69
  • 127
  • Your `array` variable is initialized properly. Now try to compare it with `fileData`. Please take look at: [how to compare the Java Byte\[\] array?](http://stackoverflow.com/questions/9499560/how-to-compare-the-java-byte-array) – wypieprz Mar 25 '15 at 18:24

1 Answers1

1

I used a ByteArrayInputStream and System.arraycopy to do the job:

package bom;

import java.io.ByteArrayInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Bom {

    public static void main(String[] args) {
        try {
            new Bom().go();
        } catch (Exception ex) {
            Logger.getLogger(Bom.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void go() throws Exception {
        //create data with BOM header:
        byte[] byteArrayBom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF, 65, 66, 67};

        ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayBom);
        if (byteArrayBom.length >= 3) {
            //read the first 3 bytes to detect BOM header:
            int b00 = bais.read();
            int b01 = bais.read();
            int b02 = bais.read();
            if (b00 == 239 && b01 == 187 && b02 == 191) { 
                //BOM detected. create new byte[] for bytes without BOM:
                byte[] contentWithoutBom = new byte[byteArrayBom.length - 3];

                //copy byte array without the first 3 bytes:
                System.arraycopy(byteArrayBom, 3, contentWithoutBom, 0, byteArrayBom.length - 3);

                //let's see what we have:
                System.out.println(new String(contentWithoutBom)); //ABC

                for (int i = 0; i < contentWithoutBom.length; i++) {
                    System.out.println(contentWithoutBom[i]); //65, 66 67
                }
            }
        }
    }
}
chris
  • 1,685
  • 3
  • 18
  • 28