【问题标题】:Initializing byte array in java在java中初始化字节数组
【发布时间】:2015-03-25 17:08:55
【问题描述】:

我有一个下面的 sn-p 可以在 Grovy 中完美运行,现在正在尝试将其转换为 java,但我得到了

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
}

我尝试将其更改如下,但出现 Incompatible operand types byte and byte[] 编译器错误

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

我从未使用过字节数组,有人可以帮我解决这个问题吗?

【问题讨论】:

标签: java byte bytearray


【解决方案1】:

我使用ByteArrayInputStreamSystem.arraycopy 来完成这项工作:

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

【讨论】:

    猜你喜欢
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 2013-01-08
    相关资源
    最近更新 更多