Tarea 11: Escritura y Lectura de Bytes con FileOutputStream y FileInputStream

Explicación del Ejercicio

En esta tarea se trabaja con flujos de bytes, que permiten manejar cualquier tipo de fichero (no solo texto). El programa escribe los bytes del 65 al 72 en un fichero binario y después los lee mostrando su valor y el carácter que representan.

Conceptos y métodos clave:

  • Escritura de bytes (FileOutputStream): El método write(int) escribe un único byte (los 8 bits menos significativos del entero recibido).
  • Lectura de bytes (FileInputStream): El método read() devuelve un valor entre 0 y 255, o -1 cuando se alcanza el final del fichero.
  • Casteo a carácter ((char) byteLeido): Los valores 65 a 72 corresponden a las letras A a H de la tabla ASCII, y el casting permite mostrarlas.
  • Cierre antes de leer: Cada flujo se abre en su propio bloque try-with-resources, de forma que el de escritura queda cerrado antes de empezar a leer.

Código Fuente y Salida

Clase10.java
package ClaseFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Eva Gallardo Romero
 * @date 25 de sep de 2026
 * Escribir en el fichero binario "bytes.dat" los bytes del 65 al 72
 * utilizando FileOutputStream y después leerlos con FileInputStream
 * mostrando el valor de cada byte y el carácter que representa.
 */
public class Clase10 {

    public static void main(String[] args) {

        // objeto File del fichero binario
        File fichero = new File("bytes.dat");

        // escribo los bytes en el fichero
        try (FileOutputStream fos = new FileOutputStream(fichero)) {

            for (int i = 65; i <= 72; i++) {
                fos.write(i);
            }

        } catch (IOException e) {
            System.out.println("Error al escribir: " + e.getMessage());
            return;
        }

        System.out.println("Bytes escritos en " + fichero.getName() + ": " + fichero.length());

        // leo los bytes uno a uno hasta que read() devuelva -1
        try (FileInputStream fis = new FileInputStream(fichero)) {

            int byteLeido;
            while ((byteLeido = fis.read()) != -1) {
                System.out.println("Byte leído: " + byteLeido + " -> " + (char) byteLeido);
            }

        } catch (IOException e) {
            System.out.println("Error al leer: " + e.getMessage());
        }
    }
}

Resultado Mostrado por Terminal

Salida de Consola
Bytes escritos en bytes.dat: 8 Byte leído: 65 -> A Byte leído: 66 -> B Byte leído: 67 -> C Byte leído: 68 -> D Byte leído: 69 -> E Byte leído: 70 -> F Byte leído: 71 -> G Byte leído: 72 -> H