0

tengo un proyecto de hacer una aplicacion de java, pero en la parte de iniciar sesion y de añadir informacion a una tabla, el arraylist (usando serializacion) solo añade un objeto y cuando intentas añadir varios, solo sobreescribe el primero y el tamaño siempre es 1. ¿cual es mi error? ¿como puedo solucionarlo? aqui pongo las funciones:

public class F_Data {
private File archivo = new File("Pandora.dat");
private ArrayList<Data> deus = new ArrayList();

public void getAllData(Date fecha, String alimentos, String ejercicio, String tipo, 
        String medicamento1, String medicamento2, String medicamento3, 
        double glucosa1, double glucosa2, double glucosa3, double glucosa4, 
        String nota1, String nota2, String nombre, String contraseña, 
        String usuario, String sexo, int edad){ 
    Data obj = new Data(fecha, alimentos, ejercicio, tipo, medicamento1,
            medicamento2, medicamento3, glucosa1, glucosa2, glucosa3, 
            glucosa4, nota1, nota2, nombre, contraseña, usuario, sexo, edad);
    deus.add(obj);

}
//es precisamente en esta parte y la de arriba en donde el array se queda estancado
public void WriteFile() throws FileNotFoundException, IOException{
    FileOutputStream fo = new FileOutputStream(archivo);
    ObjectOutputStream out = new ObjectOutputStream(fo);    
    out.writeObject(deus);      
    System.out.println("guardado");   
    System.out.println("array: "+deus.size());
    out.close();
}
public void ReadFile() throws FileNotFoundException, IOException, ClassNotFoundException{
    FileInputStream fi = new FileInputStream(archivo);
    ObjectInputStream in = new ObjectInputStream(fi);
    deus = (ArrayList)in.readObject();
    for (int j = 0; j < deus.size(); j++) {
        Data ar = deus.get(j);
        System.out.println(ar.getNombre());
    }
    in.close();

}
public double getGlucose(int y) throws IOException, ClassNotFoundException{
   FileInputStream fi = new FileInputStream(archivo);
    ObjectInputStream in = new ObjectInputStream(fi);
    deus = (ArrayList)in.readObject();
    in.close();
    Data hosk = deus.get(y);
    return hosk.getGlucosa1()+hosk.getGlucosa2()+hosk.getGlucosa3()+hosk.getGlucosa4(); 
}
public Date getDate(int x) throws IOException, ClassNotFoundException{
    FileInputStream fi = new FileInputStream(archivo);
    ObjectInputStream in = new ObjectInputStream(fi);
    deus= (ArrayList)in.readObject();
    in.close();
    Data hosk = deus.get(x);
    return hosk.getFecha();
}
public boolean login(String user,String pass) throws FileNotFoundException, IOException, ClassNotFoundException{
    FileInputStream fi = new FileInputStream(archivo);
    ObjectInputStream in = new ObjectInputStream(fi);
    deus = (ArrayList)in.readObject();
    for (int i = 0; i < deus.size(); i++) {
        Data ojo = (Data)deus.get(i);
        if (ojo.getUsuario().equals(user)&&ojo.getContraseña().equals(pass)) {
            return true;
        }
        else{
            return false;
        }
    }
    return false;
}   
}

aqui esta el otro:

ArrayList <Data> usu = new ArrayList<>();
File archivo = new File("Afrodita.dat");

public void EscribirArchivo() throws FileNotFoundException, IOException{

FileOutputStream fo = new FileOutputStream(archivo);
ObjectOutputStream salida = new ObjectOutputStream(fo);

salida.writeObject(usu);
salida.close();

}

void agregarUsuario(Date fecha,String alimentos,String ejercicio,String tipo,String medicamento1,String medicamento2,String medicamento3,
        double glucosa1, double  glucosa2, double glucosa3,double glucosa4,String nota1,String nota2) throws IOException {

    Data obj = new Data(fecha, alimentos, ejercicio, tipo, medicamento1, medicamento2, medicamento3, 
            glucosa1, glucosa2, glucosa3, glucosa4, nota1, nota2, nota2, null, null, null, 0);


    usu.add(obj);
    EscribirArchivo();



}

void leerArchivo() throws FileNotFoundException, IOException, ClassNotFoundException{

    FileInputStream fi = new FileInputStream(archivo);
    ObjectInputStream entrada = new ObjectInputStream(fi);
    usu = (ArrayList) entrada.readObject();
    for (int i = 0; i < usu.size(); i++) {
       Data neptuno = usu.get(i);

        Tabla.setValueAt(neptuno.getFecha(), i, 0);
        Tabla.setValueAt(neptuno.getAlimentos(),i, 1);
        Tabla.setValueAt(neptuno.getEjercicio(),i , 2);
        Tabla.setValueAt(neptuno.getTipo(),i, 3);
        Tabla.setValueAt(neptuno.getMedicamento1(),i, 4);
        Tabla.setValueAt(neptuno.getMedicamento2(),i, 5);
        Tabla.setValueAt(neptuno.getMedicamento3(),i, 6);
        Tabla.setValueAt(neptuno.getGlucosa1(),i, 7);
        Tabla.setValueAt(neptuno.getGlucosa2(),i, 8);
        Tabla.setValueAt(neptuno.getGlucosa3(),i, 9);
        Tabla.setValueAt(neptuno.getGlucosa4(),i, 10);
        Tabla.setValueAt(neptuno.getNota1(),i, 11);
        Tabla.setValueAt(neptuno.getNota2(),i, 12);
    }   
    entrada.close();
}
3
  • 2
    @Carmen eso no es cierto. ArrayList#add() tiene dos firmas. La primera acepta index. La segunda sólo el elemento que quieras añadir, y lo añade al final siempre, sin eliminar otros elementos.
    – David DPG
    el 28 nov. 2017 a las 9:01
  • Hola Masterhand, puedes decirnos en qué punto exactamente falla? Dónde debería añadir los elementos y no los añade? Edita tu respuesta por favor =)
    – David DPG
    el 28 nov. 2017 a las 11:11
  • Falla en la parte de WriteFile() y getAllData(), al parecer el ArrayList no se recorre y crece automaticamente cada que añade información, solo sobreescribe el primer indice. saludos. el 29 nov. 2017 a las 6:15

1 respuesta 1

0

Una manera simple:

public List<String> cargarArchivo(String direccion){
List<String>lineas = new ArrayList<>();

try {
    Path ruta = Paths.get(direccion);

    Stream<String> flujoFormateado = Files.lines(ruta, Charset.forName("UTF-8")); // cargando el archivo plano
    flujoFormateado.forEach(lineas::add); // almacenando todos los elementos para su analisis

    System.out.println("lineas guardadas: "+lineas.size());
} catch (IOException ex) {
    Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
}
return lineas;

}

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.