mercredi 28 avril 2010

java : encodage de caractère ISO-LATIN-1 vers Unicode

Voici un petit exemple de code qui vous permet d'encoder une chaine d'un charset connu au charset java standart (Unicode)


// liste tous les charsets disponibles
Map map = Charset.availableCharsets();
Iterator it = map.keySet().iterator();

while (it.hasNext()) {
// Get charset name
String charsetName = (String)it.next();

System.out.println("charset " + charsetName);

}


// convertit une chaine de ISO-8859-1 à la String Java UTF-8
String lu = new String("Saisies complémentaires ADV incomplètes".getBytes(),"ISO-8859-1");
System.out.println("" + new String(lu.getBytes("ISO-8859-1")));


Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();

try {
// Convert a string to ISO-LATIN-1 bytes in a ByteBuffer
// The new ByteBuffer is ready to be read.
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(lu));

// Convert ISO-LATIN-1 bytes in a ByteBuffer to a character ByteBuffer and then to a string.
// The new ByteBuffer is ready to be read.
CharBuffer cbuf = decoder.decode(bbuf);
String s = cbuf.toString();
System.out.println(s);
} catch (CharacterCodingException e) {
e.printStackTrace();
}

Aucun commentaire:

Enregistrer un commentaire