Sto cercando di ordinare i caratteri, la loro rappresentazione in sequenze di byte in base ai set di caratteri e come convertire da un set di caratteri all'altro in Java. Ho delle difficoltàByteBuffer, CharBuffer, String e Charset
Per esempio,
ByteBuffer bybf = ByteBuffer.wrap("Olé".getBytes());
mia comprensione è che:
- String sono sempre memorizzati come UTF-16 sequenza di byte in Java (2 byte per carattere, big endian)
getBytes()
risultato è la stessa sequenza di byte UTF-16wrap()
mantiene questa sequenzabybf
è quindi una grande rappresentazione UTF-16 endian della stringaOlé
Così in questo codice:
Charset utf16 = Charset.forName("UTF-16");
CharBuffer chbf = utf16.decode(bybf);
System.out.println(chbf);
decode()
dovrebbe
- interpretare
bybf
come una stringa UTF-16 rappresentazione - "convert" nella stringa originale
Olé
.
In realtà nessun byte deve essere modificato poiché tutto è memorizzato in UTF-16 e UTF-16 Charset
dovrebbe essere una sorta di "operatore neutro". Tuttavia il risultato viene stampato come:
??
Come può essere?
Domanda aggiuntiva: per la conversione corretta, sembra che Charset.decode(ByteBuffer bb)
richieda l'bb
come immagine di sequenza di byte big endian UTF-16 di una stringa. È corretto?
Edit: Dalle risposte fornite, ho fatto alcuni test per stampare un contenuto ByteBuffer
e la chars
ottenuto dalla decodifica. I byte [codifica con = "Olé".getBytes(charsetName)
] sono stampati sulla prima riga di gruppi, le altre linee sono le stringhe ottenute decodificando i byte [con Charset#decode(ByteBuffer)
] con vari Charset
.
Ho anche confermato che la codifica predefinita per la memorizzazione di String in byte[]
su un computer Windows 7 è windows-1252
(a meno che le stringhe non contengano caratteri che richiedono UTF-8).
Default VM encoding: windows-1252
Sample string: "Olé"
getBytes() no CS provided : 79 108 233 <-- default (windows-1252), 1 byte per char
Decoded as windows-1252: Olé <-- using the same CS than getBytes()
Decoded as UTF-16: ?? <-- using another CS (doesn't work indeed)
getBytes with windows-1252: 79 108 233 <-- same than getBytes()
Decoded as windows-1252: Olé
getBytes with UTF-8: 79 108 195 169 <-- 'é' in UTF-8 use 2 bytes
Decoded as UTF-8: Olé
getBytes with UTF-16: 254 255 0 79 0 108 0 233 <-- each char uses 2 bytes with UTF-16
Decoded as UTF-16: Olé (254-255 is an encoding tag)
la maggior parte dei sistemi Windows non esegue il comando _not_ in modo predefinito su utf-8. Inoltre, non sono sicuro di cosa intendi con "UTF-16 ish". java utilizza UTF-16. – jtahlborn
Grazie BevynQ. Attualmente sto imparando Java, la tua dimostrazione mi è stata molto utile. – mins
@jtahlborn: il mio CS predefinito era Windows-1252 fino a quando ho cambiato la stringa di esempio in "I ♥ café". Aggiungendo il cuore reso Java passare a UTF-8. Molto educativo. – mins