Convert byte array to friendly string

I have a program that processes byte arrays in Java, and now I would like to write this to an XML file. However, I'm not sure how I can convert the next byte array to a reasonable string to write to a file. Assuming these are Unicode characters, I tried to execute the following code:

String temp = new String(encodedBytes, "UTF-8");

Only for the debugger to show what encodedBytes contains "\ufffd\ufffd ^\ufffd\ufffd-m\ufffd\ufffd\/ufffd \ufffd\ufffdIA\ufffd\ufffd". The string must contain a hash in alphanumeric format.

How would I turn the above String into a reasonable string for output?

+3
source share
2 answers

( , ), , Base64, .

, , , Base 64. Commons Codec / Base64 .

, .

+7

UTF-8. , \ufffd ( REPLACEMENT CHARACTER) " , Unicode."

: , . byte ñ UTF-8, US-ASCII; ISO-8859-1. , , , String.

public class Hello {

    public static void main(String[] args)
            throws java.io.UnsupportedEncodingException {
        String s = "Hola, señor!";
        System.out.println(s);
        byte[] b = new byte[s.length()];
        for (int i = 0; i < b.length; i++) {
            int cp = s.codePointAt(i);
            b[i] = (byte) cp;
            System.out.print((byte) cp + " ");
        }
        System.out.println();
        System.out.println(new String(b, "UTF-8"));
        System.out.println(new String(b, "US-ASCII"));
        System.out.println(new String(b, "ISO-8859-1"));
    }
}

:

Hola, señor!
72 111 108 97 44 32 115 101 -15 111 114 33 
Hola, se or!
Hola, se or!
Hola, señor!
+10

Source: https://habr.com/ru/post/1741471/


All Articles