Al terminar podrás:
- Consultar y manipular rutas con la clase File
- Leer y escribir bytes con FileInputStream y FileOutputStream
- Guardar tipos primitivos con DataOutputStream
CONCEPTO
¿Qué es un flujo?
Un stream es una secuencia de datos que va de un origen a un destino. En java.io hay flujos de bytes y de caracteres.
Bytes
InputStream y OutputStream: imágenes, binarios, cualquier archivo.
Caracteres
Reader y Writer: texto. Los veremos en el tema 22.
File
Representa una ruta, no el contenido del archivo.
FILE
Consultar el sistema de archivos
File f = new File("datos/notas.txt");
boolean existe = f.exists();
boolean esCarpeta = f.isDirectory();
long bytes = f.length(); // tamaño
String nombre = f.getName(); // notas.txt
String ruta = f.getAbsolutePath();
new File("datos").mkdirs(); // crea carpetas
File[] hijos = new File("datos").listFiles();
boolean borrado = f.delete();No abre el archivo
Solo consulta y manipula la ruta.
Rutas relativas
Parten de la carpeta desde donde se ejecuta el programa.
Moderno
java.nio.file.Path y Files hacen lo mismo con mejor manejo de errores.
CLASES
Flujos de bytes
| Clase | Para qué sirve |
|---|---|
| FileInputStream / FileOutputStream | Leer y escribir bytes crudos de un archivo |
| BufferedInputStream / BufferedOutputStream | Agregan un búfer: menos accesos al disco |
| DataInputStream / DataOutputStream | Leer y escribir tipos primitivos y String |
| ObjectInputStream / ObjectOutputStream | Objetos completos (tema 23) |
Los flujos se envuelven unos en otros: new DataOutputStream(new FileOutputStream("x.dat")). Es el patrón Decorator.
COPIAR UN ARCHIVO
Leer y escribir bytes
try (InputStream in = new FileInputStream("foto.jpg");
OutputStream out = new FileOutputStream("copia.jpg")) {
byte[] buffer = new byte[4096];
int leidos;
while ((leidos = in.read(buffer)) != -1) {
out.write(buffer, 0, leidos);
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}read
Devuelve cuántos bytes leyó, o −1 al llegar al final.
Búfer
Se copia de 4 KB en 4 KB, no byte por byte.
try-with-resources
Cierra ambos flujos al terminar.
EJERCICIO GUIADO
Registro binario de temperaturas
Guarda datos con tipo y recupéralos en el mismo orden.
- Escribe en temps.dat la cantidad de registros con writeInt.
- Por cada día, escribe el nombre con writeUTF y la temperatura con writeDouble.
- Muestra cuántos bytes ocupa el archivo con File.length().
- Vuelve a leerlo con DataInputStream, en el mismo orden, y calcula el promedio.
SOLUCIÓN · 1 DE 2
Escribir
String[] dias = {"Lun", "Mar", "Mié"};
double[] temps = {27.5, 29.0, 26.5};
File archivo = new File("temps.dat");
try (DataOutputStream out = new DataOutputStream(
new FileOutputStream(archivo))) {
out.writeInt(dias.length);
for (int i = 0; i < dias.length; i++) {
out.writeUTF(dias[i]);
out.writeDouble(temps[i]);
}
}
System.out.println("Bytes escritos: " + archivo.length());Formato propio
El archivo no tiene etiquetas: solo bytes en un orden que tú decides.
throws IOException
main la declara para simplificar el ejemplo.
SOLUCIÓN · 2 DE 2
Leer en el mismo orden
try (DataInputStream in = new DataInputStream(
new FileInputStream(archivo))) {
int n = in.readInt();
double suma = 0;
for (int i = 0; i < n; i++) {
String dia = in.readUTF();
double t = in.readDouble();
System.out.println(dia + ": " + t + " °C");
suma += t;
}
System.out.printf("Promedio: %.2f °C%n", suma / n);
}Mismo orden
Si lees readDouble donde escribiste writeUTF, obtienes basura o EOFException.
readInt primero
Saber cuántos registros hay permite usar un for.
RESULTADO
Salida del programa
Consola
Bytes escritos: 44
Lun: 27.5 °C
Mar: 29.0 °C
Mié: 26.5 °C
Promedio: 27.67 °C44 bytes: 4 del int, y por día 2 de longitud + el texto (é ocupa 2 bytes) + 8 del double.
DEBER
Copiador con estadísticas
Mide el efecto del búfer y guarda datos binarios.
- Programa que copie cualquier archivo; origen y destino llegan por args.
- Mide el tiempo con System.nanoTime() copiando byte a byte y con búfer de 8 KB; compara.
- Recorre una carpeta con listFiles() y guarda nombre y tamaño de cada archivo con DataOutputStream.
- Lee ese archivo binario y muestra el archivo más grande.
Entrega: proyecto en .zip + capturas de ejecución · Fecha: [definir] · Criterios de evaluación: ver la página del curso