簡體   English   中英

Java:附加字節數組

[英]Java: Appendable byte array

我想將字節追加到字節數組。 結果應為byte[]類型,並在計算完后將其添加為單個byte 所以我的問題是:什么是最好的和/或最有效的方法? 怎么寫呢?

使用ByteArrayOutputStream。 完成后,它具有toByteArray()方法

http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html

我建議使用番石榴的ByteSource

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteSource.html

由於使用了內部的小塊鏈而不是為大型數組重新分配內存(如ByteArrayOutputStream那樣),因此效率更高。

這是一個例子:

byte[] buffer = new byte[1024]; 

List<ByteSource> loaded = new ArrayList<ByteSource>();

    while (true) {
        int read = input.read(buffer);
        if (read == -1) break;
        loaded.add(ByteSource.wrap(Arrays.copyOf(buffer, read)));
    }

ByteSource result = ByteSource.concat(loaded)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM