Java 바이트 배열에서 문자열로 바이트 배열로
byte []에서 문자열로, byte []에서 byte [] 로의 문자열 표현을 이해하려고 노력하고 있습니다 ... 나는 byte []를 보낼 문자열로 변환 한 다음 웹 서비스 (파이썬으로 작성)를 기대합니다 클라이언트로 데이터를 바로 에코합니다.
Java 애플리케이션에서 데이터를 보낼 때 ...
Arrays.toString(data.toByteArray())
보낼 바이트 ..
[B@405217f8
Send (이것은 내 바이트 데이터의 문자열 표현이어야하는 Arrays.toString ()의 결과입니다.이 데이터는 와이어를 통해 전송됩니다) :
[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]
파이썬 쪽에서 파이썬 서버는 호출자에게 문자열을 반환합니다 (볼 수있는 것은 서버에 보낸 문자열과 같습니다)
[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]
서버는이 데이터를 클라이언트로 반환해야합니다.
클라이언트가 (문자열로)받는 응답은 다음과 같습니다.
[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]
받은 문자열을 바이트로 되 돌리는 방법을 알 수없는 것 같습니다.]
내가 시도하는 것처럼 보이는 것은 다음과 같은 바이트 배열을 얻는 것입니다 ...
[91, 45, 52, 55, 44, 32, 49, 44, 32, 49, 54, 44, 32, 56, 52, 44, 32, 50, 44, 32, 49, 48, 49, 44, 32, 49, 49, 48, 44, 32, 56, 51, 44, 32, 49, 49, 49, 44, 32, 49, 48, 57, 44, 32, 49, 48, 49, 44, 32, 51, 50, 44, 32, 55, 56, 44, 32, 55, 48, 44, 32, 54, 55, 44, 32, 51, 50, 44, 32, 54, 56, 44, 32, 57, 55, 44, 32, 49, 49, 54, 44, 32, 57, 55, 93]
또는 다음과 같은 바이트 표현을 얻을 수 있습니다.
B@2a80d889
둘 다 내 보낸 데이터와 다릅니다 ... 나는 정말 간단한 것을 놓치고 있다고 확신합니다 ....
어떤 도움?
반환 된 문자열을 가져 와서 문자열을 구성 할 수는 없습니다. byte[]
더 이상 데이터 형식 이 아니며 이미 문자열입니다. 구문 분석해야합니다. 예를 들면 다음과 같습니다.
String response = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]"; // response from the Python script
String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];
for (int i=0, len=bytes.length; i<len; i++) {
bytes[i] = Byte.parseByte(byteValues[i].trim());
}
String str = new String(bytes);
** 편집 **
의 질문에서 문제의 힌트를 얻습니다. " Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ...
" 라고 말하는 곳 91
에서 바이트 값 [
이므로 [91, 45, ...
문자열 " [-45, 1, 16, ...
"문자열 의 바이트 배열도 마찬가지 입니다 .
이 메소드 Arrays.toString()
는 String
지정된 배열 의 표현을 리턴합니다 . 반환 된 값이 더 이상 배열이 아님을 의미합니다. 예를 들면 다음과 같습니다.
byte[] b1 = new byte[] {97, 98, 99};
String s1 = Arrays.toString(b1);
String s2 = new String(b1);
System.out.println(s1); // -> "[97, 98, 99]"
System.out.println(s2); // -> "abc";
보다시피 s1
, 배열 의 문자열 표현 b1
을 s2
유지하고에 포함 된 바이트 의 문자열 표현 을 유지합니다 b1
.
이제 문제에서 서버는과 비슷한 문자열을 반환 s1
하므로 배열 표현을 다시 얻으려면 반대 생성자 메서드가 필요합니다. s2.getBytes()
의 반대 인 경우 의 반대 new String(b1)
를 찾아야 Arrays.toString(b1)
하므로이 답변의 첫 번째 조각에 붙여 넣은 코드입니다.
String coolString = "cool string";
byte[] byteArray = coolString.getBytes();
String reconstitutedString = new String(byteArray);
System.out.println(reconstitutedString);
콘솔에 "cool string"을 출력합니다.
꽤 쉽습니다.
제가 한:
고객에게 반환 :
byte[] result = ****encrypted data****;
String str = Base64.encodeBase64String(result);
return str;
고객으로부터 받기 :
byte[] bytes = Base64.decodeBase64(str);
your data will be transferred in this format:
OpfyN9paAouZ2Pw+gDgGsDWzjIphmaZbUyFx5oRIN1kkQ1tDbgoi84dRfklf1OZVdpAV7TonlTDHBOr93EXIEBoY1vuQnKXaG+CJyIfrCWbEENJ0gOVBr9W3OlFcGsZW5Cf9uirSmx/JLLxTrejZzbgq3lpToYc3vkyPy5Y/oFWYljy/3OcC/S458uZFOc/FfDqWGtT9pTUdxLDOwQ6EMe0oJBlMXm8J2tGnRja4F/aVHfQddha2nUMi6zlvAm8i9KnsWmQG//ok25EHDbrFBP2Ia/6Bx/SGS4skk/0couKwcPVXtTq8qpNh/aYK1mclg7TBKHfF+DHppwd30VULpA==
What Arrays.toString()
does is create a string representation of each individual byte in your byteArray.
Please check the API documentation Arrays API
To convert your response string back to the original byte array, you have to use split(",")
or something and convert it into a collection and then convert each individual item in there to a byte to recreate your byte array.
Its simple to convert byte array to string and string back to byte array in java. we need to know when to use 'new' in the right way. It can be done as follows:
byte array to string conversion:
byte[] bytes = initializeByteArray();
String str = new String(bytes);
String to byte array conversion:
String str = "Hello"
byte[] bytes = str.getBytes();
For more details, look at: http://evverythingatonce.blogspot.in/2014/01/tech-talkbyte-array-and-string.html
The kind of output you are seeing from your byte array ([B@405217f8
) is also an output for a zero length byte array (ie new byte[0]
). It looks like this string is a reference to the array rather than a description of the contents of the array like we might expect from a regular collection's toString()
method.
As with other respondents, I would point you to the String
constructors that accept a byte[]
parameter to construct a string from the contents of a byte array. You should be able to read raw bytes from a socket's InputStream
if you want to obtain bytes from a TCP connection.
If you have already read those bytes as a String
(using an InputStreamReader
), then, the string can be converted to bytes using the getBytes()
function. Be sure to pass in your desired character set to both the String constructor and getBytes()
functions, and this will only work if the byte data can be converted to characters by the InputStreamReader
.
If you want to deal with raw bytes you should really avoid using this stream reader layer.
Can you not just send the bytes as bytes, or convert each byte to a character and send as a string? Doing it like you are will take up a minimum of 85 characters in the string, when you only have 11 bytes to send. You could create a string representation of the bytes, so it'd be "[B@405217f8", which can easily be converted to a bytes
or bytearray
object in Python. Failing that, you could represent them as a series of hexadecimal digits ("5b42403430353231376638") taking up 22 characters, which could be easily decoded on the Python side using binascii.unhexlify()
.
[JDK8]
import java.util.Base64;
To string:
String str = Base64.getEncoder().encode(new byte[]{ -47, 1, 16, ... });
To byte array:
byte[] bytes = Base64.getDecoder().decode("JVBERi0xLjQKMyAwIG9iago8P...");
If you want to convert the string back into a byte array you will need to use String.getBytes()
(or equivalent Python function) and this will allow you print out the original byte array.
Use the below code API to convert bytecode as string to Byte array.
byte[] byteArray = DatatypeConverter.parseBase64Binary("JVBERi0xLjQKMyAwIG9iago8P...");
[JAVA 8]
import java.util.Base64;
String dummy= "dummy string";
byte[] byteArray = dummy.getBytes();
byte[] salt = new byte[]{ -47, 1, 16, ... }
String encoded = Base64.getEncoder().encodeToString(salt);
참고URL : https://stackoverflow.com/questions/6684665/java-byte-array-to-string-to-byte-array
'IT' 카테고리의 다른 글
파일 대화 상자를 열고 WPF 컨트롤 및 C #을 사용하여 파일을 선택하십시오. (0) | 2020.05.23 |
---|---|
Gulp 작업에 매개 변수 전달 (0) | 2020.05.23 |
파이썬에서 하나의 목록을 다른 목록에 삽입하는 구문은 무엇입니까? (0) | 2020.05.23 |
파이썬을 사용하여 파일의 전체 디렉토리를 기존 디렉토리에 어떻게 복사합니까? (0) | 2020.05.23 |
Node.js 및 .Net 성능 (0) | 2020.05.23 |