Codificación de caracteres
Publicado por Jesús (8 intervenciones) el 29/10/2007 12:05:09
Hola, necesito transformar una cadena en un array de bytes y más tarde guardar ese array en un fichero. Tengo el siguiente trozo de código en el que se prueban varias posibilidades de codificación, pero cuando se ejecuta, en los archivos resultantes los caracteres raros se han sustituido por "?" o por cuadrados. ¿Alguien sabe qué hacer para que se almacenen bien los datos?
Muchas gracias.
String s = "Hola Jesús. ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚÀÈÌÒÙÄËÏÖÜÂÊÎÔÛ";
byte[] b = s.getBytes();
escribeAFichero(b, "c:/ficheroConUnByteArray.txt");
b = s.getBytes("latin1");
escribeAFichero(b, "c:/ficheroConUnByteArray-latin1.txt");
b = s.getBytes("UTF-8");
escribeAFichero(b, "c:/ficheroConUnByteArray_UTF-8.txt");
b = s.getBytes("ISO-8859-1");
escribeAFichero(b, "c:/ficheroConUnByteArray_ISO-8859-1.txt");
b = s.getBytes("US-ASCII");
escribeAFichero(b, "c:/ficheroConUnByteArray_US-ASCII.txt");
*********************
public static void escribeAFichero(byte[] datos, String nombreFichero){
try {
FileOutputStream fos = new FileOutputStream(new File(nombreFichero));
OutputStreamWriter fw = new OutputStreamWriter(fos);
for (int i= 0; i< datos.length; i++)
fw.write(datos[i]);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Muchas gracias.
String s = "Hola Jesús. ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚÀÈÌÒÙÄËÏÖÜÂÊÎÔÛ";
byte[] b = s.getBytes();
escribeAFichero(b, "c:/ficheroConUnByteArray.txt");
b = s.getBytes("latin1");
escribeAFichero(b, "c:/ficheroConUnByteArray-latin1.txt");
b = s.getBytes("UTF-8");
escribeAFichero(b, "c:/ficheroConUnByteArray_UTF-8.txt");
b = s.getBytes("ISO-8859-1");
escribeAFichero(b, "c:/ficheroConUnByteArray_ISO-8859-1.txt");
b = s.getBytes("US-ASCII");
escribeAFichero(b, "c:/ficheroConUnByteArray_US-ASCII.txt");
*********************
public static void escribeAFichero(byte[] datos, String nombreFichero){
try {
FileOutputStream fos = new FileOutputStream(new File(nombreFichero));
OutputStreamWriter fw = new OutputStreamWriter(fos);
for (int i= 0; i< datos.length; i++)
fw.write(datos[i]);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Valora esta pregunta


0