3

Buenas, estoy haciendo un ejercicio en el cual debo agregar unos objetos a un fichero usando un método y otro metodo para buscarlos usando el nombre que se le haya dado.

Os pongo los métodos y clases:

Clase Artículo, este es el Objeto a insertar.

public class Articulo implements Serializable{

private String nombre;
private int cantidad;
private double precioUnidad;

public Articulo(String nombre, int cantidad, double precioUnidad){
    this.nombre=nombre;
    this.cantidad=cantidad;
    this.precioUnidad=precioUnidad;
}

public String getNombre() {
    return nombre;
}

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

public int getCantidad() {
    return cantidad;
}

public void setCantidad(int cantidad) {
    this.cantidad = cantidad;
}

public double getPrecioUnidad() {
    return precioUnidad;
}

public void setPrecioUnidad(double precioUnidad) {
    this.precioUnidad = precioUnidad;
}

public void vende(int num) throws NoDisponible{
    if(this.cantidad>0){
        this.cantidad=this.cantidad-num;
    }else{
        throw new NoDisponible("No hay artículos disponibles");
    }
}

public String toString(){
    return "El articulo se llama "+nombre+" y hay "+cantidad;
}
}

Esta es la clase Tienda, con los métodos insertar y busca:

public class Tienda {

String directorio="C://Users//prh19//Desktop//tienda.txt";
ObjectOutputStream ficheroObjeto=null;
ObjectInputStream ficheroObjetoLectura=null;

public void insertar(Articulo a){
    try {
        ficheroObjeto=new ObjectOutputStream(new FileOutputStream(directorio,true));
        ficheroObjeto.writeObject(a);
        System.out.println("Objeto insertado correctamente");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        if(ficheroObjeto!=null){
            try{
                ficheroObjeto.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

public Articulo busca(String nombreArticulo) throws NoExiste{
    Articulo articulo=null;
    try {
        ficheroObjetoLectura=new ObjectInputStream(new FileInputStream(directorio));
        articulo=(Articulo) ficheroObjetoLectura.readObject();
        while(articulo!=null){
            if(articulo instanceof Articulo){

                articulo=(Articulo) ficheroObjetoLectura.readObject();
                if(articulo.getNombre().equals(nombreArticulo)){
                    return articulo;
                }else{
                    throw new NoExiste("Ese articulo no existe");
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }finally{
        if(ficheroObjetoLectura!=null){
            try {
                ficheroObjetoLectura.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return articulo;

}
}

Esta es mi clase main:

public class PruebaTienda {

public static void main(String[] args) throws NoExiste {

    Tienda tienda=new Tienda();
    Articulo a1=new Articulo("Patatas",0,10.5);
    Articulo a2=new Articulo("Tomates",5,1.5);
    Articulo a3=new Articulo("Ajos",456,40.5);
    Articulo a4=new Articulo("Olivas",45,10.90);
    Articulo a5=new Articulo("Carne",23,9.87);
    Articulo a6=new Articulo("Lechuga",89,11.56);

    tienda.insertar(a1);
    tienda.insertar(a2);
    tienda.insertar(a3);
    tienda.insertar(a4);
    tienda.insertar(a5);
    tienda.insertar(a6);
    System.out.println(tienda.busca("Patatas"));
    System.out.println(tienda.busca("Tomates"));
}

}

A la hora de insertar un Artículo no tengo problema, el problema viene a la hora de buscarlo, que obtengo esto:

java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(Unknown Source)
 El articulo se llama Patatas y hay 0
at java.io.ObjectInputStream.readObject(Unknown Source)
at examenfebrero.Tienda.busca(Tienda.java:39)
at examenfebrero.PruebaTienda.main(PruebaTienda.java:21)  


java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at examenfebrero.Tienda.busca(Tienda.java:39)
at examenfebrero.PruebaTienda.main(PruebaTienda.java:22)
El articulo se llama Patatas y hay 0
3
  • estoy casi seguro que no esta encontrando a tu archivo de esta direccion "C://Users//prh19//Desktop//tienda.txt"; el 15 feb. 2017 a las 14:10
  • El directorio está bien, porque a la hora de insertar funciona y el .txt se llena.
    – NeoChiri
    el 15 feb. 2017 a las 14:57
  • El problema esta en el momento de escribir los objetos. Consulta este enlace discoduroderoer.es/serializacion-de-objetos-en-java
    – secundaria
    el 23 mar. 2018 a las 9:15

2 respuestas 2

1

Tienes un error en el método busca (en el finally), tienes que cerrar ficheroObjetoLectura y no ficheroObjeto. Deberías usar la notación

try(ObjectInputStream  ficheroObjetoLectura=new ObjectInputStream(new FileInputStream(directorio))){
...
}

Así te ahorras la gestión manual del close():

public Articulo busca(String nombreArticulo) throws NoExiste{
    Articulo articulo=null;
    try(FileOutputStream miFOS = new FileOutputStream(directorio)){
        try(ObjectInputStream  ficheroObjetoLectura=new ObjectInputStream(miFOS)){
            articulo=(Articulo) ficheroObjetoLectura.readObject();
            while(articulo!=null){
                if(articulo instanceof Articulo){

                    articulo=(Articulo) ficheroObjetoLectura.readObject();
                    if(articulo.getNombre().equals(nombreArticulo)){
                        return articulo;
                    }else{
                        throw new NoExiste("Ese articulo no existe");
                    }
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
            e.printStackTrace();
    }
    return articulo;

}
2
  • Sigo teniendo el mismo problema si hago eso.
    – NeoChiri
    el 15 feb. 2017 a las 14:57
  • He editado la respuesta, prueba a ver ahora. el 16 feb. 2017 a las 9:32
0

creo que tienes que resetear, prueba poniendo esto

if(ficheroObjeto!=null){
            try {
                ficheroObjeto.close();
                ficheroObjeto.reset();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
1
  • No funciona con eso e incluso me saca otra excepción: java.io.IOException: mark/reset not supported at java.io.InputStream.reset(Unknown Source) at examenfebrero.Tienda.busca(Tienda.java:55) at examenfebrero.PruebaTienda.main(PruebaTienda.java:21)
    – NeoChiri
    el 15 feb. 2017 a las 15:48

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.