**If there are some non italian readers that wish to learn more about java encoding please leave a comment in english and I’ll try to post more articles (english readable) on the topic.**
Ho visto che molte delle ricerche che portano al blog hanno le parole chiava java ed encoding. Ho pensato di dedicare qualche post all’argomento.
Il primo e’: Come cambiare encoding ad un file?
Faccio copia ed incolla di un sorgente Java che preso un file con un certo encoding (da specificare esplicitamente) ne crea una sua versione con un encoding differente.
public class FileReEncoder {
private static final int BUFFER_SIZE=2048;
public static void main(String[] args) throws Exception {
String fileNameIn=”test1″;
String fileNameOut=”test2″;
String encodingIn=”UTF-8″;
String encodingOut=”ISO-8859-1″;
File fileIn=new File(fileNameIn);
if (!fileIn.exists() || !fileIn.canRead()) {
System.err.println(”Il file ” + fileNameIn + ” non esiste o è illeggibile”);
System.exit(-1);
}
FileInputStream fis= new FileInputStream(fileIn);
InputStreamReader reader= new InputStreamReader(fis,Charset.forName(encodingIn));
try {
FileOutputStream fos=new FileOutputStream(fileNameOut);
OutputStreamWriter writer= new OutputStreamWriter(fos, Charset.forName(encodingOut));
try {
char[] bufferChar=new char[BUFFER_SIZE];
int charsRead=0;
while ((charsRead=reader.read(bufferChar))>0) {
writer.write(bufferChar, 0, charsRead);
}
} finally {
writer.close();
}
} finally {
reader.close();
}
}
}
Enjoy!
Se ci sono altre domande o cose che vorreste vedere trattate sull’argomento suggerite pure.
**If there are some non italian readers that wish to learn more about java encoding please leave a comment in english and I’ll try to post more articles (english readable) on the topic.**