import org.apache.commons.io.IOUtils;
public class Iconv {
public static void iconv(InputStream in, OutputStream out, Charset inCharset, Charset outCharset) throws IOException {
InputStreamReader reader = new InputStreamReader(in,inCharset);
OutputStreamWriter writer = new OutputStreamWriter(out,outCharset);
IOUtils.copy(reader,writer);
writer.close();
}
Cómo se usa:
public static void main(String[] args) throws Exception {
utf8ToLatin1();
latin1ToUtf8();
}
private static void latin1ToUtf8() throws Exception {
FileInputStream in = new FileInputStream("/home/pablo/Desktop/workspace/test/files/textoLatin1.txt");
FileOutputStream out = new FileOutputStream("/tmp/textoLatin1ToUTF8.txt");
iconv(in, out, Charset.forName("latin1"), Charset.forName("UTF-8"));
out.close();
}
private static void utf8ToLatin1() throws Exception {
FileInputStream in = new FileInputStream("/home/pablo/Desktop/workspace/test/files/textoUTF8.txt");
FileOutputStream out = new FileOutputStream("/tmp/textoUTF8ToLatin1.txt");
iconv(in, out, Charset.forName("UTF-8"), Charset.forName("latin1"));
out.close();
}
Entrada:
pablo@pablo-desktop:~/Desktop/workspace/test/files$ file --mime texto*
textoLatin1.txt: text/plain; charset=iso-8859-1
textoUTF8.txt: text/plain; charset=utf-8
Resultado:
pablo@pablo-desktop:~/Desktop/workspace/test/files$ file --mime /tmp/texto*
/tmp/textoLatin1ToUTF8.txt: text/plain; charset=utf-8
/tmp/textoUTF8ToLatin1.txt: text/plain; charset=iso-8859-1