Quando abbiamo la necessità di leggere uno stream di byte è molto importante definire il tipo di codifica se i byte rappresentano un flusso di caratteri. La codifica viene applicata alle classi InputStream, OutputStream (orientati ai byte), poiché le classi Reader, Writer sono di per sé orientate ai caratteri. Sono di grande aiuto le classi wrapper InputStreamReader, OutputStreamWriter.
Di seguito riporto un esempio di codice corretto:
BufferedReader br = new BufferedReader(new InputStreamReader(msg,"UTF-8"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(baos, "UTF-8");
Writer w = new BufferedWriter(osw);
char[] buffer = new char[4096]; // 2^12
int len;
while ((len = br.read(buffer)) != -1) {
w.write(buffer, 0, len);
}
br.close();
w.close();
In questo modo la lettura e scrittura è codificata in UTF-8 e le performance sono ottimizzate dalle classi BufferedReader e BufferedWriter
N.B. I charset che Java riconosce sono solo quelli IANA (http://www.iana.org/assignments/character-sets). Per osesrvare i Charset accettati vedere qui. Per esempio per settare la codifica utf-8 è necessario settare “UTF-8″; ma se chiediamo a Java ..getEncoding()=UTF8!
Un piccolo trucco quando si incontra il carattere € (non lo vedi? è l’Euro).. per salvarlo su db con codifica non AL32UTF8 ma WE8ISO8859P1 è questo:
// eventuale inserimento del carattere euro
byte[] bytes = <StringaConEuro>.getBytes("ISO-8859-15");
String stringBytes = new String(bytes, "ISO-8859-15");
byte[] bytesEuro = new byte[1];
bytesEuro[0] = -92;
String euro = new String(bytesEuro,"ISO-8859-15");
stringBytes = stringBytes.replaceAll(euro, " Euro");
Un’ altra soluzione:
// Create the encoder and decoder for ISO-8859-15
Charset charset = Charset.forName("ISO-8859-15");
ByteBuffer bbuf = charset.encode(CharBuffer.wrap(notISOString));
CharBuffer cbuf = charset.decode(bbuf);
tmpISOString = cbuf.toString();
log.debug("tmpISOString = " + tmpISOString);
http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/Charset.html
A tal proposito riporto il noto Bush hid the facts