[英]Byte array of unknown length in java
我在java中構造一個字節數組,我不知道數組會有多長。
我想要一些像Java的StringBuffer這樣的工具你可以調用.append(字節b)或.append(byte [] buf)並讓它緩沖我的所有字節並在完成后返回給我一個字節數組。 是否有一個類用於StringBuffer為字符串做什么? 它看起來不像我正在尋找的ByteBuffer類。
誰有一個很好的解決方案?
嘗試ByteArrayOutputStream
。 你可以使用write( byte[] )
,它會根據需要增長。
只是為了擴展前面的答案,你可以使用ByteArrayOutputStream和它的方法public void write(byte[] b, int off, int len)
,其中參數是:
b - 數據
off - 數據中的起始偏移量
len - 要寫入的字節數
如果要將其用作“字節構建器”並逐字節插入,則可以使用:
byte byteToInsert = 100;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(new byte[]{byteToInsert}, 0, 1);
然后你可以使用baos.toString()
方法將數組轉換為字符串。 優點是當您需要設置輸入的編碼時,您可以簡單地使用ie:
baos.toString("Windows-1250")
我寫了一個非常容易使用的,並避免了大量的字節數組緩沖區復制。
它有一個名為add的方法。
您可以向其添加字符串,字節,字節,長整數,整數,雙精度,浮點數,短整數和字符。
API易於使用,並且有些失敗。 它不允許您復制緩沖區,也不會促進擁有兩個讀取器。
它有一個邊界檢查模式和我知道我做什么模式沒有邊界檢查。
邊界檢查模式會自動增長,因此沒有麻煩。
https://github.com/RichardHightower/boon/wiki/Auto-Growable-Byte-Buffer-like-a-ByteBuilder
以下是有關如何使用它的完整分步指南。 它在github上。
你有沒有想過一個易於使用的緩沖陣列自動增長和/或你可以給它一個固定大小,只是添加東西? 我有。 我也寫了一個。
看..我可以寫字符串(它將它們轉換為UTF-8)。
ByteBuf buf = new ByteBuf();
buf.add(bytes("0123456789\n"));
buf.add("0123456789\n");
buf.add("0123456789\n");
buf.add("0123456789\n");
buf.add("0123456789\n");
buf.add("0123456END\n");
然后我可以讀出緩沖區中的字符串:
String out = new String(buf.readAndReset(), 0, buf.len());
assertEquals(66, buf.len());
assertTrue(out.endsWith("END\n"));
我永遠不必設置數組的大小。 它將以有效的方式根據需要自動增長。
如果我確切地知道我的數據有多大,我可以使用createExact保存一些邊界檢查。
ByteBuf buf = ByteBuf.createExact(66);
buf.add(bytes("0123456789\n"));
buf.add("0123456789\n");
buf.add("0123456789\n");
buf.add("0123456789\n");
buf.add("0123456789\n");
buf.add("0123456END\n");
assertEquals(66, buf.len());
如果我使用create exact,那么我就說...嘿..我知道它到底有多大,它永遠不會超過這個數字,如果它確實...你可以用麻袋打我的頭岩石!
下面用一袋石頭打你的頭! 發出異常!!!!
ByteBuf buf = ByteBuf.createExact(22);
buf.add(bytes("0123456789\n"));
buf.add("0123456789\n");
buf.add("0123456789\n");
buf.add("0123456789\n");
buf.add("0123456789\n");
buf.add("0123456END\n");
它適用於雙打。
ByteBuf buf = ByteBuf.createExact(8);
//add the double
buf.add(10.0000000000001);
byte[] bytes = buf.readAndReset();
boolean worked = true;
worked |= idxDouble(bytes, 0) == 10.0000000000001 || die("Double worked");
它適用於浮動。
ByteBuf buf = ByteBuf.createExact(8);
//add the float
buf.add(10.001f);
byte[] bytes = buf.readAndReset();
boolean worked = true;
worked |= buf.len() == 4 || die("Float worked");
//read the float
float flt = idxFloat(bytes, 0);
worked |= flt == 10.001f || die("Float worked");
它適用於int。
ByteBuf buf = ByteBuf.createExact(8);
//Add the int to the array
buf.add(99);
byte[] bytes = buf.readAndReset();
boolean worked = true;
//Read the int back
int value = idxInt(bytes, 0);
worked |= buf.len() == 4 || die("Int worked length = 4");
worked |= value == 99 || die("Int worked value was 99");
它適用於char。
ByteBuf buf = ByteBuf.createExact(8);
//Add the char to the array
buf.add('c');
byte[] bytes = buf.readAndReset();
boolean worked = true;
//Read the char back
int value = idxChar(bytes, 0);
worked |= buf.len() == 2 || die("char worked length = 4");
worked |= value == 'c' || die("char worked value was 'c'");
它適用於短期。
ByteBuf buf = ByteBuf.createExact(8);
//Add the short to the array
buf.add((short)77);
byte[] bytes = buf.readAndReset();
boolean worked = true;
//Read the short back
int value = idxShort(bytes, 0);
worked |= buf.len() == 2 || die("short worked length = 2");
worked |= value == 77 || die("short worked value was 77");
它甚至適用於字節。
ByteBuf buf = ByteBuf.createExact(8);
//Add the byte to the array
buf.add( (byte)33 );
byte[] bytes = buf.readAndReset();
boolean worked = true;
//Read the byte back
int value = idx(bytes, 0);
worked |= buf.len() == 1 || die("byte worked length = 1");
worked |= value == 33 || die("byte worked value was 33");
您可以將各種基元添加到字節數組中。
boolean worked = true;
ByteBuf buf = ByteBuf.create(1);
//Add the various to the array
buf.add( (byte) 1 );
buf.add( (short) 2 );
buf.add( (char) 3 );
buf.add( 4 );
buf.add( (float) 5 );
buf.add( (long) 6 );
buf.add( (double)7 );
worked |= buf.len() == 29 || die("length = 29");
byte[] bytes = buf.readAndReset();
byte myByte;
short myShort;
char myChar;
int myInt;
float myFloat;
long myLong;
double myDouble;
現在我們只是驗證我們可以讀回所有內容。
myByte = idx ( bytes, 0 );
myShort = idxShort ( bytes, 1 );
myChar = idxChar ( bytes, 3 );
myInt = idxInt ( bytes, 5 );
myFloat = idxFloat ( bytes, 9 );
myLong = idxLong ( bytes, 13 );
myDouble = idxDouble ( bytes, 21 );
worked |= myByte == 1 || die("value was 1");
worked |= myShort == 2 || die("value was 2");
worked |= myChar == 3 || die("value was 3");
worked |= myInt == 4 || die("value was 4");
worked |= myFloat == 5 || die("value was 5");
worked |= myLong == 6 || die("value was 6");
worked |= myDouble == 7 || die("value was 7");
一旦你打電話
byte[] bytes = buf.readAndReset()
然后你說你完成了ByteBuffer!
一旦你要求字節,它就變得無用,因為它將內部字節數組設置為空。
當你調用readAndReset時,它會給你它的緩沖區。 這是我的內部狀態,你可以擁有它,但我將它設置為null,所以沒有其他人使用它。
沒關系。 如果您確定一次只有一個實例使用緩沖區(byte []),則創建另一個實例。
您甚至可以使用剛剛使用的緩沖區
ByteBuf buf2 = new ByteBuf.create(bytes);
這是因為沒有復制緩沖區。 ByteBuf寫入您提供的緩沖區。 如果您希望將另一個副本提供給ByteBuf,請執行以下操作:
ByteBuf buf2 = new ByteBuf.create( copy(bytes) );
畢竟這是恩惠。 :)
快來看看吧。 你得到上面的類和idx,以及免費的idxInt和idxLong!
讓我們來看看。 Java中有ByteBuffer類。
http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html
它具有批量方法,可將連續的字節序列從字節數組傳輸到硬件緩沖區。 它會成功。
它還具有絕對和相對的get和put方法,用於讀取和寫入byte [] s和其他原語到/用於字節緩沖區。
它還具有壓縮,復制和切片字節緩沖區的方法。
// Creates an empty ByteBuffer with a 1024 byte capacity
ByteBuffer buf = ByteBuffer.allocate(1024);
// Get the buffer's capacity
int capacity = buf.capacity(); // 10
buf.put((byte)0xAA); // position=0
// Set the position
buf.position(500);
buf.put((byte)0xFF);
// Read the position 501
int pos = buf.position();
// Get remaining byte count
int remaining = buf.remaining(); (capacity - position)
它還有一個批量放置數組,這非常接近你要求的追加:
public final ByteBuffer put(byte[] src)
請參閱:http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#put(byte [])
我編寫了自己的小lib來操作字節數組。 :)
您可以像這樣添加它們
byte [] a = ...
byte [] b = ...
byte [] c = ...
a = add(a, b);
a = add(a, c);
這將為你提供b的所有內容,以及c之后的內容。
如果你想增加21,你可以做以下事情:
a = grow( letters, 21);
如果您想將a的大小加倍,可以執行以下操作:
a = grow( letters, 21);
看到...
https://github.com/RichardHightower/boon/blob/master/src/main/java/org/boon/core/primitive/Byt.java
byte[] letters =
arrayOfByte(500);
assertEquals(
500,
len(letters)
);
創建
byte[] letters =
array((byte)0, (byte)1, (byte)2, (byte)3);
assertEquals(
4,
len(letters)
);
指數
byte[] letters =
array((byte)'a', (byte)'b', (byte)'c', (byte)'d');
assertEquals(
'a',
idx(letters, 0)
);
assertEquals(
'd',
idx(letters, -1)
);
assertEquals(
'd',
idx(letters, letters.length - 1)
);
idx(letters, 1, (byte)'z');
assertEquals(
(byte)'z',
idx(letters, 1)
);
包含
byte[] letters =
array((byte)'a',(byte) 'b', (byte)'c', (byte)'d');
assertTrue(
in((byte)'a', letters)
);
assertFalse(
in((byte)'z', letters)
);
切片:
byte[] letters =
array((byte)'a', (byte)'b', (byte)'c', (byte)'d');
assertArrayEquals(
array((byte)'a', (byte)'b'),
slc(letters, 0, 2)
);
assertArrayEquals(
array((byte)'b', (byte)'c'),
slc(letters, 1, -1)
);
//>>> letters[2:]
//['c', 'd']
//>>> letters[-2:]
//['c', 'd']
assertArrayEquals(
array((byte)'c', (byte)'d'),
slc(letters, -2)
);
assertArrayEquals(
array((byte)'c', (byte)'d'),
slc(letters, 2)
);
//>>> letters[:-2]
// ['a', 'b']
assertArrayEquals(
array((byte)'a', (byte)'b'),
slcEnd(letters, -2)
);
//>>> letters[:-2]
// ['a', 'b']
assertArrayEquals(
array((byte)'a',(byte) 'b'),
slcEnd(letters, 2)
);
增長
byte[] letters =
array((byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e');
letters = grow( letters, 21);
assertEquals(
'e',
idx(letters, 4)
);
assertEquals(
'a',
idx(letters, 0)
);
assertEquals(
len(letters),
26
);
assertEquals(
'\0',
idx(letters, 20)
);
收縮:
letters = shrink ( letters, 23 );
assertArrayEquals(
array((byte)'a', (byte)'b', (byte)'c'),
letters
);
復制:
assertArrayEquals(
array((byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e'),
copy(array((byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e'))
);
加:
assertArrayEquals(
array((byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f'),
add(array((byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e'), (byte)'f') );
添加實際上通過使用System.arraycopy將它們添加到一起(考慮不安全,但尚未)。
將一個數組添加到另一個:
assertArrayEquals(
array( (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f'),
add( array((byte)'a', (byte)'b', (byte)'c', (byte)'d'), array((byte)'e', (byte)'f') )
);
插入:
assertArrayEquals(
array((byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g'),
insert( array((byte)'a', (byte)'b', (byte)'d', (byte)'e', (byte)'f', (byte)'g'), 2, (byte)'c' )
);
assertArrayEquals(
array((byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g'),
insert( array((byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g'), 0, (byte)'a' )
);
assertArrayEquals(
array((byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g'),
insert( array((byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'g'), 5, (byte)'f' )
);
以下是一些方法:
public static byte[] grow(byte [] array, final int size) {
Objects.requireNonNull(array);
byte [] newArray = new byte[array.length + size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
public static byte[] grow(byte [] array) {
Objects.requireNonNull(array);
byte [] newArray = new byte[array.length *2];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
public static byte[] shrink(byte[] array, int size) {
Objects.requireNonNull(array);
byte[] newArray = new byte[array.length - size];
System.arraycopy(array, 0, newArray, 0, array.length-size);
return newArray;
}
public static byte[] copy(byte[] array) {
Objects.requireNonNull(array);
byte[] newArray = new byte[array.length];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
public static byte[] add(byte[] array, byte v) {
Objects.requireNonNull(array);
byte[] newArray = new byte[array.length + 1];
System.arraycopy(array, 0, newArray, 0, array.length);
newArray[array.length] = v;
return newArray;
}
public static byte[] add(byte[] array, byte[] array2) {
Objects.requireNonNull(array);
byte[] newArray = new byte[array.length + array2.length];
System.arraycopy(array, 0, newArray, 0, array.length);
System.arraycopy(array2, 0, newArray, array.length, array2.length);
return newArray;
}
public static byte[] insert(final byte[] array, final int idx, final byte v) {
Objects.requireNonNull(array);
if (idx >= array.length) {
return add(array, v);
}
final int index = calculateIndex(array, idx);
//Object newArray = Array.newInstance(array.getClass().getComponentType(), array.length+1);
byte [] newArray = new byte[array.length+1];
if (index != 0) {
/* Copy up to the location in the array before the index. */
/* src sbegin dst dbegin length of copy */
System.arraycopy( array, 0, newArray, 0, index );
}
boolean lastIndex = index == array.length -1;
int remainingIndex = array.length - index;
if (lastIndex ) {
/* Copy the area after the insert. Make sure we don't write over the end. */
/* src sbegin dst dbegin length of copy */
System.arraycopy(array, index, newArray, index + 1, remainingIndex );
} else {
/* Copy the area after the insert. */
/* src sbegin dst dbegin length of copy */
System.arraycopy(array, index, newArray, index + 1, remainingIndex );
}
newArray[index] = v;
return newArray;
}
public static byte[] insert(final byte[] array, final int fromIndex, final byte[] values) {
Objects.requireNonNull(array);
if (fromIndex >= array.length) {
return add(array, values);
}
final int index = calculateIndex(array, fromIndex);
//Object newArray = Array.newInstance(array.getClass().getComponentType(), array.length+1);
byte [] newArray = new byte[array.length + values.length];
if (index != 0) {
/* Copy up to the location in the array before the index. */
/* src sbegin dst dbegin length of copy */
System.arraycopy( array, 0, newArray, 0, index );
}
boolean lastIndex = index == array.length -1;
int toIndex = index + values.length;
int remainingIndex = newArray.length - toIndex;
if (lastIndex ) {
/* Copy the area after the insert. Make sure we don't write over the end. */
/* src sbegin dst dbegin length of copy */
System.arraycopy(array, index, newArray, index + values.length, remainingIndex );
} else {
/* Copy the area after the insert. */
/* src sbegin dst dbegin length of copy */
System.arraycopy(array, index, newArray, index + values.length, remainingIndex );
}
for (int i = index, j=0; i < toIndex; i++, j++) {
newArray[ i ] = values[ j ];
}
return newArray;
}
更多....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.