문제

Java에는 문자열이 있고 이를 바이트 배열(UTF8 또는 기타 인코딩)로 인코딩하고 싶습니다.또는 바이트 배열(일부 알려진 인코딩)이 있고 이를 Java 문자열로 변환하고 싶습니다.이러한 변환을 어떻게 수행합니까?

도움이 되었습니까?

해결책

문자열에서 바이트[]로 변환:

String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);

byte[]에서 문자열로 변환:

byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, StandardCharsets.US_ASCII);

물론 올바른 인코딩 이름을 사용해야 합니다.내 예제에서는 가장 일반적인 두 가지 인코딩인 US-ASCII와 UTF-8을 사용했습니다.

다른 팁

모든 전환에 대해 문자 집합 조회를 수행하지 않는 솔루션은 다음과 같습니다.

import java.nio.charset.Charset;

private final Charset UTF8_CHARSET = Charset.forName("UTF-8");

String decodeUTF8(byte[] bytes) {
    return new String(bytes, UTF8_CHARSET);
}

byte[] encodeUTF8(String string) {
    return string.getBytes(UTF8_CHARSET);
}
String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");

다음을 통해 직접 변환할 수 있습니다. 문자열(바이트[], 문자열) 생성자와 getBytes(String) 메소드.Java는 다음을 통해 사용 가능한 문자 세트를 노출합니다. 문자셋 수업.JDK 문서 지원되는 인코딩 목록.

90%의 경우 이러한 변환은 스트림에서 수행되므로 다음을 사용합니다. 리더/작가 클래스.임의의 바이트 스트림에서 String 메소드를 사용하여 증분적으로 디코딩하지 않을 것입니다. 멀티바이트 문자와 관련된 버그에 노출될 수 있습니다.

내 tomcat7 구현은 문자열을 ISO-8859-1로 허용합니다.HTTP 요청의 콘텐츠 유형에도 불구하고.다음 솔루션은 'é' 와 같은 문자를 올바르게 해석하려고 할 때 효과적이었습니다.

byte[] b1 = szP1.getBytes("ISO-8859-1");
System.out.println(b1.toString());

String szUT8 = new String(b1, "UTF-8");
System.out.println(szUT8);

문자열을 US-ASCII로 해석하려고 하면 바이트 정보가 올바르게 해석되지 않았습니다.

b1 = szP1.getBytes("US-ASCII");
System.out.println(b1.toString());

대안으로, StringUtils Apache Commons에서 사용할 수 있습니다.

 byte[] bytes = {(byte) 1};
 String convertedString = StringUtils.newStringUtf8(bytes);

또는

 String myString = "example";
 byte[] convertedBytes = StringUtils.getBytesUtf8(myString);

비표준 문자 세트가 있는 경우 다음을 사용할 수 있습니다. getBytesUnchecked() 또는 새로운문자열() 따라서.

일련의 바이트를 일반 문자열 메시지로 디코딩하기 위해 마침내 다음 코드를 사용하여 UTF-8 인코딩으로 작업하게 되었습니다.

/* Convert a list of UTF-8 numbers to a normal String
 * Usefull for decoding a jms message that is delivered as a sequence of bytes instead of plain text
 */
public String convertUtf8NumbersToString(String[] numbers){
    int length = numbers.length;
    byte[] data = new byte[length];

    for(int i = 0; i< length; i++){
        data[i] = Byte.parseByte(numbers[i]);
    }
    return new String(data, Charset.forName("UTF-8"));
}

7비트 ASCII 또는 ISO-8859-1(놀랍도록 일반적인 형식)을 사용하는 경우 새 파일을 만들 필요가 없습니다. java.lang.문자열 조금도.단순히 바이트를 char로 변환하는 것이 훨씬 더 성능이 좋습니다.

전체 작업 예:

for (byte b : new byte[] { 43, 45, (byte) 215, (byte) 247 }) {
    char c = (char) b;
    System.out.print(c);
}

당신이있는 경우 ~ 아니다 사용하여 확장 문자 ä, Æ, Å, Ç, Ï, ت 같은 그리고 전송된 값이 처음 128개의 유니코드 문자인지 확신할 수 있으면 이 코드는 UTF-8 및 확장 ASCII(예: cp-1252)에서도 작동합니다.

//query is your json   

 DefaultHttpClient httpClient = new DefaultHttpClient();
 HttpPost postRequest = new HttpPost("http://my.site/test/v1/product/search?qy=");

 StringEntity input = new StringEntity(query, "UTF-8");
 input.setContentType("application/json");
 postRequest.setEntity(input);   
 HttpResponse response=response = httpClient.execute(postRequest);

댓글을 달 수는 없지만 새 스레드를 시작하고 싶지는 않습니다.그러나 이것은 작동하지 않습니다.간단한 왕복 여행:

byte[] b = new byte[]{ 0, 0, 0, -127 };  // 0x00000081
String s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000,  0x0000, 0xfffd
b = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081

b[] 인코딩 전후에 동일한 배열이 필요하지만 그렇지 않습니다(이것은 첫 번째 답변을 나타냅니다).

Charset UTF8_CHARSET = Charset.forName("UTF-8");
String strISO = "{\"name\":\"א\"}";
System.out.println(strISO);
byte[] b = strISO.getBytes();
for (byte c: b) {
    System.out.print("[" + c + "]");
}
String str = new String(b, UTF8_CHARSET);
System.out.println(str);
Reader reader = new BufferedReader(
    new InputStreamReader(
        new ByteArrayInputStream(
            string.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));

정말 늦었지만 방금 이 문제가 발생했고 이것이 제가 해결한 방법입니다.

private static String removeNonUtf8CompliantCharacters( final String inString ) {
    if (null == inString ) return null;
    byte[] byteArr = inString.getBytes();
    for ( int i=0; i < byteArr.length; i++ ) {
        byte ch= byteArr[i]; 
        // remove any characters outside the valid UTF-8 range as well as all control characters
        // except tabs and new lines
        if ( !( (ch > 31 && ch < 253 ) || ch == '\t' || ch == '\n' || ch == '\r') ) {
            byteArr[i]=' ';
        }
    }
    return new String( byteArr );
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top