vendredi 27 avril 2012

Java encoding (UTF) tips and tricks




Starts Java with default encoding for streams :

java ... -Dfile.encoding=UTF-8 ...


Read a file encoded in :

File inputFile = new File("...");
BufferedReader myFileReader = new BufferedReader(new InputStreamReader(new FileInputStream (inputFile), Charset.forName("UTF-8")));


Write a file with encoding :

File outputFile = new File("...");
BufferedWriter myFileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile),Charset.forName("UTF-8")));



Convert bytes to String using encoding :

byte[] stringBytes = ...;
String convertedString = new String(stringBytes,Charset.forName("UTF-8"));          



Convert String to bytes using encoding :

String myString = ...;          
byte[] stringBytes = myString.getBytes(Charset.forName("UTF-8"));



To be continued ...





Contrat Creative Commons
the jee architect cookbook by Olivier SCHMITT est mis à disposition selon les termes de la licence Creative Commons Paternité - Pas d'Utilisation Commerciale - Pas de Modification 3.0 Unported.

Aucun commentaire:

Enregistrer un commentaire