import java.io.*;
// Leer.class debe estar en la carpeta especificada por CLASSPATH

public class CrearAlumnos
{
  public static void crearFichero(File fichero)
    throws IOException
  {
    PrintStream flujoS = System.out; // salida estándar
    DataOutputStream dos = null;// salida de datos hacia el fichero
    char resp;
    try
    {
      // Crear un flujo hacia el fichero que permita escribir
      // datos de tipos primitivos y que utilice un buffer.
      dos = new DataOutputStream(new BufferedOutputStream(
                                 new FileOutputStream(fichero)));

      // Declarar los datos a escribir en el fichero
      int númeroMatrícula;
      String nombre;
      String calificación;

      // Leer datos de la entrada estándar y escribirlos
      // en el fichero
      do
      {
        flujoS.print("Nº de matrícula:                ");
        númeroMatrícula = Leer.datoInt();
        flujoS.print("Nombre:                         ");
        nombre = Leer.dato();
        flujoS.print("Calificación (SS, AP, NT o SB): ");
        calificación = Leer.dato();
            
        // Almacenar un registro en el fichero
        dos.writeInt(númeroMatrícula);
        dos.writeUTF(nombre);
        dos.writeUTF(calificación);
            
        flujoS.print("¿desea escribir otro registro? (s/n) ");
        resp = (char)System.in.read();
        // Saltar los caracteres disponibles en el flujo de entrada
        System.in.skip(System.in.available());
      }
      while (resp == 's');
    }
    finally
    {
      // Cerrar el flujo
      if (dos != null) dos.close();
    }
  }

  public static void main(String[] args)
  {
    PrintStream flujoS = System.out; // salida estándar
    String nombreFichero = null;     // nombre del fichero
    File fichero = null; // objeto que identifica el fichero
    
    try
    {
      // Crear un objeto File que identifique al fichero
      flujoS.print("Nombre del fichero: ");
      nombreFichero = Leer.dato();
      fichero = new File(nombreFichero);
      
      // Verificar si el fichero existe
      char resp = 's';
      if (fichero.exists())
      {
        flujoS.print("El fichero existe ¿desea sobreescribirlo? (s/n) ");
        resp = (char)System.in.read();
        // Saltar los caracteres disponibles en el flujo de entrada
        System.in.skip(System.in.available());
      }
      if (resp == 's')
      {
        crearFichero(fichero);
      }
    }
    catch(IOException e)
    {
      flujoS.println("Error: " + e.getMessage());
    }
  }
}
