문제
나를 구성하는 바이트 배열에 자바고 내가 알지 못하는 방법을 배가 될 것입니다.
내가 원하는 도구는 자바의 StringBuffer 할 수있는 전화.append(byte 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")
내가 쓴 하는 것은 정말 쉽게 사용하고 많이 피할 수의 바이트 배열의 버퍼에 복사할 수 있습니다.
그것은 하나의 방법이라고 추가합니다.
추가할 수 있습니다 문자열,바이,바이트 길이,int,더블,float,짧은 문자니다.
API 를 사용하기 쉽고 약간은 실패에 안전합니다.그렇지 않을 복사할 수 있도록 주변의 버퍼하지 않을 촉진하는 두 개의 독자.
그것은 경계 모드 확인하고 내가 무엇을 알고 내가 하는 모드이 없는 범위를 확인합니다.
범위를 확인 모드로 자동이 성장함에 따라 그것은 없기 때문입니다.
https://github.com/RichardHightower/boon/wiki/Auto-Growable-Byte-Buffer-like-a-ByteBuilder
여기에 완벽한 단계별 안내에 그것을 사용하는 방법.그것은습니다.
Java 보탬-자동할 경우 확장 가능한 바이트 버퍼처럼 ByteBuilder
당신이 이제까지 사용하기 쉬운 버퍼에 있는 배열을 자동으로 증가하 및/또는 당신이 그것을 줄 수정 크기와 그냥 물건을 추가하지?니다.썼습니다!
Look..내가 쓸 수 있는 문자열이다(이것은 그들을 변환 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());
내가 사용하는 경우를 만들 정확한 후,내가 말하고...이봐..난 정확히 얼마나 큰지 그것은 성장할 수 있고 가지 않을 것입니다 이 번호 및 않는 경우가 있습니다 나를 통해 머리를 자루의 바위!
다음과 같은 당신의 머리를 자루의 바위!예외가 발생!!!!
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");
그것은 작품이다.
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에는 바이트 버퍼 클래스가 있습니다.
http://docs.oracle.com/javase/7/docs/api/java/nio/bytebuffer.html
바이트 어레이에서 하드웨어 버퍼로 연속 바이트 시퀀스를 전송하는 벌크 방법이 있습니다. 그것은 트릭을 할 것입니다.
또한 바이트 버퍼를 위해 / 기타 프리미티브를 읽고 쓰는 방법과 상대적으로 Get and Put을 가지고 있습니다.
또한 바이트 버퍼를 압축, 복제 및 슬라이싱하는 방법이 있습니다.
// 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);
이것은 A에 대한 내용 후 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') );
ADD는 실제로 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;
}
더....