Java:如何“修剪”字节数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1919059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:25:32  来源:igfitidea点击:

Java: How to "trim" a byte array?

javafilefile-iobytearraybyte

提问by Erin Drummond

So I have some code that reads a certain amount of bytes from a file and returns the resulting byte array (this is basically used for chunking up files to send over the network as (eventually) base64-encoded ascii text).

所以我有一些代码可以从文件中读取一定数量的字节并返回结果字节数组(这基本上用于将文件分块以作为(最终)base64 编码的 ascii 文本通过网络发送)。

It works fine, except that when the last chunk of the file is generated, it isnt a full chunk. Therefore, the resulting byte array isnt full. However, it is a constant size, which means that the file is reassembled there is a whole bunch of extra data (0's maybe) appended to the end.

它工作正常,除了生成文件的最后一个块时,它不是一个完整的块。因此,生成的字节数组未满。然而,它是一个常量大小,这意味着文件被重新组装,最后附加了一大堆额外的数据(可能是 0)。

How can I make it so that the byte[] for the last chunk of the file really only contains the data it needs to? The code looks like this:

我怎样才能使文件最后一个块的字节 [] 真正只包含它需要的数据?代码如下所示:

 private byte[] readData(File f, int startByte, int chunkSize) throws Exception {
    RandomAccessFile raf = new RandomAccessFile(f, "r");
    raf.seek(startByte);
    byte[] data = new byte[chunkSize];
    raf.read(data);        
    raf.close();
    return data;
}

So if chunkSize is bigger than the remaining bytes in the file, a full sized byte[] gets returned but its only half-full with data.

因此,如果 chunkSize 大于文件中剩余的字节,则会返回一个完整大小的 byte[] ,但它只有半满的数据。

采纳答案by Asaph

You'll have to check the return value of RandomAccessFile.read()to determine the number of bytes read. If it's different than the chunkSize, you'll have to copy the array over to a smaller one and return that.

您必须检查 的返回值RandomAccessFile.read()以确定读取的字节数。如果它与 chunkSize 不同,则必须将数组复制到较小的数组并返回。

private byte[] readData(File f, int startByte, int chunkSize) throws Exception {
    RandomAccessFile raf = new RandomAccessFile(f, "r");
    raf.seek(startByte);
    byte[] data = new byte[chunkSize];
    int bytesRead = raf.read(data);
    if (bytesRead != chunkSize) {
         byte[] smallerData = new byte[bytesRead];
         System.arraycopy(data, 0, smallerData, 0, bytesRead);
         data = smallerData;
    }
    raf.close();
    return data;
}

回答by notnoop

RandomAccessFile.read()returns the number of bytes read, so you can do copy the array if needed:

RandomAccessFile.read()返回读取的字节数,因此您可以根据需要复制数组:

private byte[] readData(File f, int startByte, int chunkSize) throws Exception {
    RandomAccessFile raf = new RandomAccessFile(f, "r");
    raf.seek(startByte);
    byte[] data = new byte[chunkSize];
    int read = raf.read(data);
    raf.close();
    if (read == data.length) return data;
    else
      return Arrays.copyOf(data, read);
}

If you are using Java pre-6, then you need to implement Arrays.copyOfyourself:

如果您使用的是 Java pre-6,那么您需要Arrays.copyOf自己实现:

byte[] r = new byte[read];
System.arraycopy(data, 0, r, 0, read);
return r;

回答by user85421

You could also use the size of the file to calculate the remaining number of bytes.

您还可以使用文件的大小来计算剩余的字节数。

private byte[] readData(File f, int startByte, int chunkSize) throws Exception {
    RandomAccessFile raf = new RandomAccessFile(f, "r");
    raf.seek(startByte);
    int size = (int) Math.min(chunkSize, raf.length()-startByte);
    byte[] data = new byte[size];
    raf.read(data);
    // TODO check the value returned by read (throw Exception or loop)
    raf.close();
    return data;
}

This way you don't create an additional Array and do not need the copy. Probably not a big impact.
One important point IMO: check the value returned by read, I think it can be less than the remaining bytes. The javadoc states:

这样您就不会创建额外的数组,也不需要副本。估计影响不大。
重要的一点 IMO:检查 返回的值read,我认为它可以小于剩余字节。javadoc 指出:

The number of bytes read is, at most, equal to the length of b

读取的字节数最多等于 b 的长度