0

Stringにデータを割り当てbyte array、先頭に4バイトの文字列データ長を配置したいと思います。達成するための最良の方法は何ですか?ソケット接続を介してバイトデータを送信するためにこれが必要です。サーバー側は、最初に言及された数のバイトを読み取ります。

これを行うためのより良い方法はありますか?

private byte[] getDataSendBytes(String data) {
    int numberOfDataBytes = data.getBytes().length;

    ByteBuffer bb = ByteBuffer.allocate(HEADER_LENGTH_BYTES);
    bb.putInt(numberOfDataBytes);
    byte[] headerBytes = bb.array();
    byte[] dataBytes = data.getBytes();

    // create a Datagram packet
    byte[] sendDataBytes = new byte[HEADER_LENGTH_BYTES + dataBytes.length];

    System.arraycopy(headerBytes, 0, sendDataBytes, 0, headerBytes.length);
    System.arraycopy(dataBytes, 0, sendDataBytes, headerBytes.length,
            dataBytes.length);
    return sendDataBytes;
}
4

1 に答える 1

1

どちらかを使用します DataOutputStream

public byte[] getDataSendBytes(String text) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        new DataOutputStream(baos).writeUTF(text);
    } catch (IOException e) {
        throw new AssertionError(e);
    }
    return baos.toByteArray();
}

または、長さのタイプとエンディアンを制御するための ByteBuffer。

public byte[] getDataSendBytes(String text) {
    try {
        byte[] bytes = text.getBytes("UTF-8");
        ByteBuffer bb = ByteBuffer.allocate(4 + bytes.length).order(ByteOrder.LITTLE_ENDIAN);
        bb.putInt(bytes.length);
        bb.put(bytes);
        return bb.array();
    } catch (UnsupportedEncodingException e) {
        throw new AssertionError(e);
    }
}

またはパフォーマンスのために、ByteBuffer を再利用し、ISO-8859-1 文字エンコーディングを想定します

// GC-less method.
public void writeAsciiText(ByteBuffer bb, String text) {
    assert text.length() < (1 << 16);
    bb.putShort((short) text.length());
    for(int i=0;i<text.length();i++)
        bb.put((byte) text.charAt(i));
}
于 2012-07-20T07:07:00.927 に答える