0

如何在短缓冲区中读/写?

我正在尝试为短值实现 BufferedReader 和 Writer。每次将传递一个短 [] 并将读取一个短 []。

但是java API没有这个接口,只有byte[]。

实现此功能的最佳方法是什么?

4

4 回答 4

1

您可以使用长度为 2 的 ByteBuffer 读取/写入字节并将两组转换为短裤:

ByteBuffer put() to put the bytes into or putShort() when going the other way.   
ByteBuffer.getShort() to convert back into shorts.
于 2012-12-03T17:27:12.533 回答
1

好吧,对于您的 BufferedInputStream (不是阅读器),您可以尝试同时读取 2 个字节:

public synchronized int read(short[] s, int off, int len) throws IOException {
    byte[] b = new byte[s.length * 2];
    int read = read(b, off * 2, len * 2);
    for (int i = 0; i < read; i+=2) {
        int b1 = b[i];
        int b2 = b[i+1];
        s[i/2] = (short) ((b1 << 8) | b2);
    }
    return read / 2;
}

对于您的 BufferedOutputStream(不是 writer),您可以尝试反向操作同时写入 2 个字节。

于 2012-12-03T17:36:07.430 回答
0

您可以实现Reader 接口,然后扩展writer 类以实现除 short[] 之外的 writer。

于 2012-12-03T17:22:37.713 回答
0

Just wrap a DataOutputStream around a BufferedOutputStream, and implement a method writeShortArray(short[]) that calls writeShort() iteratively over the array argument. Similarly for input.

于 2012-12-03T22:20:25.473 回答