2014-04-25 12 views
0

: 지금은 바이트에서 Channel을 제거하기 위해 노력하고있어자바 : 바이트 배열에서 첫 번째 UTF 문자열을 제거 내가 바이트 배열로부터 서면 문자열을 제거하고 원래 별도의 개체를 유지하기 위해 노력하고있어

byte[] data... // this is populated with the following: 
// 00094E6966747943686174001C00074D657373616765000B4372616674656446757279000474657374 
// to string using converter : " ChannelMessageUsernametest" 
// notice that tab/whitespace, ignore quotes 
// The byte array was compiled by writing the following (writeUTF from a writer): 
// Channel 
// Message 
// Username 
// test 

을 배열 : 나는 분리를 잃게하는 방법을 참조하십시오

byte[] newData = Arrays.copyOfRange(data, channel.length() + 2, data.length) 
// I use Arrays.copyOfRange to strip the whitespace (I assume it's not needed) 
// As well, since it's inclusive of length size, I have to add 1 more, 
// resulting in channel.length() + 1 
// ... 
ByteArrayDataInput newInput = ByteStreams.newDataInput(message); 
String channel = newInput.readUTF(); // MessageUsernametext 

: 여기

ByteArrayDataInput input = ByteStreams.newDataInput(message); 
String channel = input.readUTF(); // Channel, don't want this 
String message = input.readUTF(); // Message 
// works good, but I don't want Channel, 
// and I can't remove it from the data before it arrives, 
// I have to work with what I have 

내 문제입니다 개체의 원본 "섹션"을 원래 byte[] data 안에있는 byte[] newData 안에 보관할 수 있습니까?

  • String channel은 (이전과 제거 후) 문자열 그것이

답변

1

때문에, 모든 객체가 문자열이라고 가정 모두가 랜덤 가정 안전하지

  • 이 있다고 가정하는 것이 안전 channel이 항상 합리적인 문자 범위 (예 : 영숫자)에 있음을 보장 할 수있는 한 channel.length() + 2channel.length() + 4으로 변경하면 충분합니다.

  • 0

    자바 문자열은 16 비트 요소를 가지고, 그래서 아니지만 효율적인 메모리로, 바이트 배열을 문자열로 변환하는 것이 안전합니다 :

    private byte[] removeElements(byte[] data, int fromIndex, int len) { 
         String str1 = new String(data).substring(0,fromIndex); 
         String str2 = new String(data).substring(fromIndex+len,data.length); 
         return (str1+str2).getBytes(); 
    } 
    

    같은 방식으로, 당신은 또한 문자열을 검색 할 수 있습니다 바이트 배열 내부 :

    private int findStringInByteArray(byte[] mainByte, String str, int fromIndex) { 
        String main = new String(mainByte); 
        return main.indexOf(str,fromIndex); 
    } 
    

    이제 이러한 방법을 함께 호출 할 수 있습니다

    byte[] newData = removeElements(
        data, 
        findStringInByteArray(data,channel,0), 
        channel.length());