Error java.io.EOFException when reading from file

1

When you called the PasarAVector() method I get the title error. This is the code of my program:

package poo_archivos1;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JOptionPane;

public class Poo_archivos1 {

    static FileOutputStream fos; //objeto para guardar el nombre del archivo a crear
    static DataOutputStream dos;
    static String nomArch = "Barcos.dat";
    static byte bar;
    static Barcos[] barco = new Barcos[10];
    static FileInputStream fis;//objeto para traer el nombre del archivo a crear
    static DataInputStream dis;//objeto para decirte donde esta el datos del archivo a crear

    public static void GuardaBarco(Barcos b) throws FileNotFoundException, IOException {
        fos = new FileOutputStream(nomArch, true);
        dos = new DataOutputStream(fos);
        dos.writeInt(b.getClave());
        dos.writeUTF(b.getNombre());
        dos.writeUTF(b.getPaisAdquisicion());
        dos.writeUTF(b.getFechaAdquisicion());
        dos.writeFloat(b.getPeso());
        dos.close();
        fos.close();
    }

    public static void RegistrarBarco() throws Exception {
        Barcos b;
        boolean ban;
        do {
            try {
                b = new Barcos();
                b.setClave(Integer.parseInt(JOptionPane.showInputDialog("Teclea la clave del barco:")));
                b.setNombre(JOptionPane.showInputDialog("Teclea el nombre del barco:"));
                b.setPaisAdquisicion(JOptionPane.showInputDialog("Teclea el pais de adquisicion del barco:"));
                b.setFechaAdquisicion(JOptionPane.showInputDialog("Teclea la fecha de adquisicion del barco:"));
                b.setPeso(Float.parseFloat(JOptionPane.showInputDialog("Teclea el Peso del barco:")));
                GuardaBarco(b);
                break;
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "Has intentado meter una letra" + e.toString());
                ban = true;
            }

        } while (ban = true);
    }

    public static void DesplegarDatos() throws FileNotFoundException, IOException {
        fis = new FileInputStream(nomArch);
        dis = new DataInputStream(fis);
        JOptionPane.showMessageDialog(null, "Reporte de los barcos regisrtrados");
        while (dis.available() != 0) {
            Barcos b = new Barcos();
            b.setClave(dis.readInt());
            b.setNombre(dis.readUTF());
            b.setPaisAdquisicion(dis.readUTF());
            b.setFechaAdquisicion(dis.readUTF());
            b.setPeso(dis.readFloat());
            JOptionPane.showMessageDialog(null, b.ConsultarDatos());
        }
        fis.close();
        dis.close();
    }

    public static void buscaClave() throws FileNotFoundException, IOException {
        fis = new FileInputStream(nomArch);
        dis = new DataInputStream(fis);
        Barcos b = new Barcos();

        int clave = Integer.parseInt(JOptionPane.showInputDialog("Teclea la clave:"));

        while (dis.available() != 0) {
            b.setClave(dis.readInt());
            b.setNombre(dis.readUTF());
            b.setFechaAdquisicion(dis.readUTF());
            b.setPaisAdquisicion(dis.readUTF());
            b.setPeso(dis.readFloat());
            System.out.println(b.ConsultarDatos());
        }

        if (clave == b.getClave()) {
            JOptionPane.showMessageDialog(null, "Si se encontro el barco");
        } else {
            JOptionPane.showMessageDialog(null, "No se encontro el barco");
        }

        fis.close();
        dis.close();
    }

    public static void PasarAVector() throws FileNotFoundException, IOException {
        bar = 1;
        try {
            fis = new FileInputStream(nomArch);
            dis = new DataInputStream(fis);
            Barcos b = new Barcos();
            while (dis.available() != 0) {
                b.setClave(dis.readInt());
                b.setNombre(dis.readUTF());
                b.setPeso(dis.readFloat());

                bar++;
                barco[bar] = b;
                System.out.println(barco[bar].ConsultarDatos());
            }
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "Sin Datos");
        }
        fis.close();
        dis.close();
    }

    public static void ConsultarVector() throws FileNotFoundException, IOException, NullPointerException {
        try {
            for (int x = 0; x < 10; x++) {
                JOptionPane.showMessageDialog(null, barco[x].ConsultarDatos());
            }
        } catch (NullPointerException e) {
            JOptionPane.showMessageDialog(null, "No tiene datos");
        }
    }

    public Poo_archivos1() throws Exception {
        int opc;
        do {
            opc = JOptionPane.showOptionDialog(null, "Elegir opcion ", "Barcos",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    new Object[]{"Registrar", "Consultar", "Buscar", "Pasar", "consultavector", "Salir"},
                    null);
            switch (opc) {
                case 0:
                    RegistrarBarco();
                    break;
                case 1:
                    DesplegarDatos();
                    break;
                case 2:
                    buscaClave();
                    break;
                case 3:
                    PasarAVector();
                    break;
                case 4:
                    ConsultarVector();
                    break;
            }
        } while (opc != 5);
    }

    public static void main(String[] args) throws Exception {
        Poo_archivos1 arc = new Poo_archivos1();
    }
}

And the image that I took to the method:

    
asked by Fernando Amezcua 15.12.2016 в 22:51
source

1 answer

1

Instead of writing to the file field by field you could serialize the entire object. Now as you need a list of Ships, you could use a ArrayList<Barco> to enter all the ships. The idea is to have the list in memory and when the program finishes, the changes are saved. This is how you serialize% complete% of%:

Class Main

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class Main {

    private final String FILENAME = "Barcos.dat";
    private ArrayList<Barco> barcos;

    public Main() throws Exception {

        if (!cargarBarcos()) {
            barcos = new ArrayList<>();
        }

        String[] opciones = new String[]{
            "Registrar",
            "Buscar",
            "consultavector",
            "Salir"
        };

        while (seleccionarAccion(
                JOptionPane.showOptionDialog(
                        null,
                        "Elegir opcion ",
                        "Barcos",
                        JOptionPane.YES_NO_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        opciones,
                        null)));
        guardarBarcos();
    }

    private boolean seleccionarAccion(int opc) throws IOException {
        switch (opc) {
            case 0:
                RegistrarBarco();
                break;
            case 1:
                buscaClave();
                break;
            case 2:
                ConsultarVector();
                break;
            case 3:
                return false;
        }
        return true;
    }

    public void RegistrarBarco() {
        Barco b = new Barco();

        while (true) {
            try {
                b.setClave(Integer.parseInt(JOptionPane.showInputDialog("Teclea la clave del barco:")));
                b.setNombre(JOptionPane.showInputDialog("Teclea el nombre del barco:"));
                b.setPaisAdquisicion(JOptionPane.showInputDialog("Teclea el pais de adquisicion del barco:"));
                b.setFechaAdquisicion(JOptionPane.showInputDialog("Teclea la fecha de adquisicion del barco:"));
                b.setPeso(Float.parseFloat(JOptionPane.showInputDialog("Teclea el Peso del barco:")));
                barcos.add(b);
                break;
            } catch (NumberFormatException e) {
                mError(null, "Has intentado meter un caracter no válido");
            }
        }
    }

    public void buscaClave() {
        Barco b = new Barco(Integer.parseInt(JOptionPane.showInputDialog("Teclea la clave:")));
        int clave = barcos.indexOf(b);

        if (clave > -1) {
            mInfo("Si se encontro el barco", barcos.get(clave).toStringFull());
        } else {
            mSimple("No se encontro el barco");
        }
    }

    public void ConsultarVector() {
        mSimple("Reporte de los barcos registrados");

        for (Barco b : barcos) {
            mInfo("Informacion de Barco", b.toStringFull());
        }
    }

    void guardarBarcos() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILENAME))) {
            oos.writeObject(barcos);
            oos.flush();
        } catch (IOException ex) {
            mError("Error al guardar", "No se ha podido guardar correctamente.");
        }
    }

    private boolean cargarBarcos() {
        try (ObjectInputStream oos = new ObjectInputStream(new FileInputStream(FILENAME))) {
            barcos = (ArrayList<Barco>) oos.readObject();
            return true;
        } catch (IOException ex) {
            mError("Error al cargar", "No se ha podido cargar correctamente.");
        } catch (ClassNotFoundException | ClassCastException ex) {
            mError("Error al cargar", "No se ha encontrado la clase o el archivo es incompatible.");
        }
        return false;
    }

    void mError(String titulo, String mensaje) {
        if (titulo == null) {
            titulo = "Error";
        }

        JOptionPane.showMessageDialog(null, mensaje, titulo, JOptionPane.ERROR_MESSAGE);
    }

    void mSimple(String s) {
        JOptionPane.showMessageDialog(null, s);
    }

    void mInfo(String titulo, String mensaje) {
        JOptionPane.showMessageDialog(null, mensaje, titulo, JOptionPane.INFORMATION_MESSAGE);
    }

    public static void main(String[] args) throws Exception {
        Main arc = new Main();
    }
}

Boat Class

import java.io.Serializable;

class Barco implements Serializable {

    private static final long serialVersionUID = 1L;

    private int clave;
    private String nombre;
    private String paisAdq;
    private String fechaAdq;
    private float peso;

    public Barco() {
    }

    public Barco(int clave) {
        this.clave = clave;
    }

    void setClave(int clave) {
        this.clave = clave;
    }

    void setNombre(String nombre) {
        this.nombre = nombre;
    }

    void setPaisAdquisicion(String pais) {
        this.paisAdq = pais;
    }

    void setFechaAdquisicion(String fecha) {
        this.fechaAdq = fecha;
    }

    void setPeso(float peso) {
        this.peso = peso;
    }

    int getClave() {
        return clave;
    }

    String getNombre() {
        return nombre;
    }

    String getPaisAdquisicion() {
        return paisAdq;
    }

    String getFechaAdquisicion() {
        return fechaAdq;
    }

    float getPeso() {
        return peso;
    }

    @Override
    public String toString() {
        return "Id: " + clave
                + "\tNombre: " + nombre;
    }

    public String toStringFull() {
        return "Id: " + clave
                + "\nNombre: " + nombre
                + "\nPais: " + paisAdq
                + "\nFecha: " + fechaAdq
                + "\nPeso: " + peso;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Barco) {
            return ((Barco) obj).clave == this.clave;
        } else {
            return this == obj;
        }
    }
}

There are some things that are not all right, you should improve them. I just left them like this to adapt the example.

    
answered by 23.12.2016 в 02:57