viernes
ago142015
Java 7: leyendo ficheros indicando el encoding

El escenario es el siguiente: tenemos un fichero de texto, desarrollado en codificación UTF-8, que debemos leer en nuestro sistema.
El contenido del fichero es el siguiente:
abcdefghijklmnñopqrstuvwxyz
áéíóú
pingüino
Para realizar la lectura, ejecutamos el siguiente código:
01.
package
javahispano;
02.
03.
import
java.io.IOException;
04.
import
java.nio.charset.Charset;
05.
import
java.nio.file.Files;
06.
import
java.nio.file.Path;
07.
import
java.nio.file.Paths;
08.
import
java.util.List;
09.
10.
public
class
Main {
11.
12.
private
static
final
String FILE =
"pruebasEncodingJava7_UTF8.txt"
;
13.
private
static
final
String PATH =
"/home/jaimecl/Documentos/pruebas/"
;
14.
private
static
final
String UTF_8 =
"UTF-8"
;
15.
private
static
final
String ISO_8859_1 =
"ISO-8859-1"
;
16.
17.
public
static
void
main(String args[]) {
18.
19.
/* Obtenemos el fichero */
20.
Path file = Paths.get(PATH, FILE);
21.
22.
try
{
23.
/*
24.
* Leemos todas las líneas del mismo en con encoding ISO_8859_1 y
25.
* mostramos la información por pantalla
26.
*/
27.
Charset charsetISO88591 = Charset.forName(ISO_8859_1);
28.
29.
System.out.println(
"\nLeyendo el fichero con encoding "
30.
+ ISO_8859_1 +
"\n"
);
31.
List<string> linesISO88591 = Files.readAllLines(file,
32.
charsetISO88591);
33.
34.
for
(String lineISO88591 : linesISO88591) {
35.
System.out.println(lineISO88591);
36.
}
37.
38.
/* Análogo al punto anterior, con encoding UTF_8 */
39.
Charset charsetUTF8 = Charset.forName(UTF_8);
40.
System.out.println(
"\nLeyendo el fichero con encoding "
+ UTF_8
41.
+
"....\n"
);
42.
43.
List<string> linesUTF8 = Files.readAllLines(file, charsetUTF8);
44.
45.
for
(String lineUTF8 : linesUTF8) {
46.
System.out.println(lineUTF8);
47.
}
48.
49.
}
catch
(IOException e) {
50.
System.out.println(e);
51.
}
52.
}
53.
}
54.
}
55.
</string></string>
¿Cuál es la salida del mismo?
Leyendo el fichero con encoding ISO-8859-1
abcdefghijklmnñopqrstuvwxyz
áéÃóú
pingüino
Leyendo el fichero con encoding UTF-8....
abcdefghijklmnñopqrstuvwxyz
áéíóú
pingüino
Como podemos ver, esta característica puede ser de mucha utilidad en estos casos. ¡A tener en cuenta, developers!
Reader Comments (1)
Con Java7 puedes mejorar el tema de algunos charsets, los que se garantiza que existirán en las distintas plataformas:
* StandardCharsets.ISO_8859_1
* StandardCharsets.UTF_8
No hay necesidad de recuperarlos mediante:
Charset charsetISO88591 = Charset.forName(ISO_8859_1);
Más información en el javadoc correspondiente.