2014-07-03 29 views
0

我想將字節附加到字節數組。 結果應該是byte[],在計算之後加入單個byte。 所以我的問題是: 什麼是最好的和/或有效的方式來完成呢? 如何寫信給那個?Java:可附加字節數組

+0

我發現下面的鏈接 http://stackoverflow.com/questions/5368704/appending-a-byte-to-the-end-of-另一個字節 認爲它可以幫助。 – user3245329

+0

你知道有多少字節嗎? –

+0

字節數可能會變化,並且在初始化時未知。 – luckydonald

回答

0

我會建議使用番石榴的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)