elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  al serializar, se sobreescriben los objetos, como puedo solucionarlo?
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: al serializar, se sobreescriben los objetos, como puedo solucionarlo?  (Leído 5,584 veces)
Kenkox

Desconectado Desconectado

Mensajes: 12



Ver Perfil
al serializar, se sobreescriben los objetos, como puedo solucionarlo?
« en: 27 Agosto 2012, 18:54 pm »

Aqui hay 4 clases, una clase se llama StudentsRegister, la cual implementa a la interfaz Serializable, tiene 3 variables de instancia con sus respectivos metodos get y set.... esa clase la he revisado, y esta perfectamente echa.
La siguiente clase se llama DesSer, la cual ayuda a serializar y deserializar en el archivo... tiene un metodo que se llama setList.. la cual llama al metodo writeObject(); para escribir la lista que se recibe  en el archivo.. ademas tiene un metodo llamado getList, la cual regresa un ArrayList<StudentsRegister> ( este metodo desserializa el archivo, y utiliza al metodo readObject
..
despues esta la clase ABC.. esta clase esta incompleta, no puedo completarla ya que tengo un problema con las altas ( agregar alumnos a un arrayList y escribirlo en un archivo )
La clase ABC tiene al metodo addStudents... primero pido cuantos alumnos se van a agregar, y despues , estos datos se utilizan para inicializar cada miembro del  array register, al momento de inicializarlos los agrega al arrayList..... al momento de que se introdujeron todos los datos de los estudiantes, se llama al metodo setList de la clase DesSer para escribir esta lista en el archivo.... este proceso esta bien.. o por lo menos no he notado ningun error... incluso en el metodo setList puse un println para poner si se han guardado los datos... y si aparece...

despues esta la clase TestABC... el cual contiene el metodo principal.. creamos un objeto ABC... y llamamos al metodo addStudents y al metodo showStudents.... TOODO sucede correctamente, me pide el numero de los alumnos, yo introdusco los datos de los alumnos, y los escribe en el archivo... sin embargo, el problema radica al volver a ejecutar TestABC, por segunda vez introdusco  alumnos nuevos ..  dice que los escribio, despues me muestra los alumnos pero SOLO me muestra a los alumnos que acababa de agregar y NO los que ya habia agregado en la primera ejecucion.. trate de solucionarlo modificando al metodo getList.. pero sigue sobreescribiendolos...

Alguien podria decirme porque sucede esto? y como podria solucionarlo?? osea, que al momento de que llame al metodo showStudents, me muestre a todos los alumnos( objetos ) que ya he agregada anteriormente

De antemano, Gracias

Código
  1. package abc;
  2.  
  3. import java.io.IOException;
  4.  
  5. /**
  6.  *
  7.  * @author Kenkox
  8.  */
  9. public class TestABC {
  10.   public static void main( String args[] ) throws IOException{
  11.      ABC proyect = new ABC();
  12.      proyect.addStudents();
  13.      proyect.showStudents();
  14.  
  15.   }
  16. }
  17.  
Código
  1. package abc;
  2. /**
  3.  *
  4.  * @author Kenkox
  5.  */
  6. import java.io.IOException;
  7. import java.util.*;
  8. public class ABC {
  9.  
  10.    /**
  11.      * @param args the command line arguments
  12.      */
  13.  
  14. private static List<StudentsRegister> studentList = new ArrayList<>();
  15. private static StudentsRegister register[];
  16.    private DesSer working = new DesSer();
  17. private Scanner keyboard = new Scanner( System.in );
  18. private String firstName;
  19. private String surname;
  20. private double mark;
  21. private int option;
  22.  
  23. public void addStudents(){
  24. System.out.println("Insert the number of Students to add ");
  25. final int TOTAL_STUDENTS = keyboard.nextInt();
  26. register = new StudentsRegister[TOTAL_STUDENTS];
  27. for( int i=0; i < register.length; i++ ){
  28. System.out.printf("%s\n%s", "write the name, surname and the mark of the student.", ":? " );
  29. firstName = keyboard.next();
  30. surname = keyboard.next();
  31. mark = keyboard.nextDouble();
  32. register[i] = new StudentsRegister(firstName, surname, mark );
  33.                studentList.add(register[i]);
  34. }
  35.            working.setList( studentList );
  36. }
  37.  
  38. public void consultar(){
  39.  
  40. }
  41.  
  42. public void eliminarAlumnos(){
  43.  
  44. }
  45.  
  46. public void modificarAlumnos(){
  47.  
  48. }
  49. public void showStudents() throws IOException{
  50. updateList();
  51. System.out.printf("%-10s%-15s%-15s%11s\n ","Num. List", "Name", "Surname", "Mark");
  52. for( int i= 0; i < studentList.size(); i++ )
  53. System.out.printf("%-10d%s\n",i + 1, studentList.get(i));
  54. }
  55. public void updateList() throws IOException{
  56. studentList = ( ArrayList<StudentsRegister> ) working.getList();
  57. }
  58.  
  59. }
  60.  
Código
  1. package abc;
  2. /**
  3.  *
  4.  * @author Kenkox
  5.  */
  6. import java.io.Serializable;
  7. public class StudentsRegister implements Serializable{
  8.     private String name;
  9. private String surname;
  10. private double mark;
  11. public StudentsRegister(){
  12. this( "", "", 0.0 );
  13. }
  14. public StudentsRegister( String name, String sur, double mk ){
  15. setName( name );
  16. setSurname( sur );
  17. setMark( mk );
  18. }
  19. public void setName( String nm){
  20. name = nm;
  21. }
  22. public String getName(){
  23. return name;
  24. }
  25. public void setSurname( String sur){
  26. surname = sur;
  27. }
  28. public String getSurname(){
  29. return surname;
  30. }
  31. public void setMark( double mk ){
  32. mark  = mk;
  33. }
  34. public double getMark(){
  35. return mark;
  36. }
  37.  
  38. public String toString(){
  39. return String.format("%-15s%-15s%11.2f\n ", getName(),
  40. getSurname(), getMark());
  41. }
  42. }
  43.  
Código
  1. package abc;
  2.  
  3.  
  4. /**
  5.  *
  6.  * @author Kenkox
  7.  */
  8. import java.io.*;
  9. import java.util.*;
  10. public class DesSer {
  11.  
  12. private ObjectOutputStream output;
  13. private ObjectInputStream input;
  14. private String fileName = "StudentsRegister.ser";
  15.    private List<StudentsRegister> temporalList = new ArrayList<>();
  16.    private List<StudentsRegister> temporalList2 = new ArrayList<>();
  17.  
  18.  
  19. public void openFileSerialize(){
  20. try{
  21. output = new ObjectOutputStream( new FileOutputStream( fileName ));
  22.  
  23. }
  24.  
  25. catch( Exception e ){
  26. System.out.printf("there was an error opening the File: \" %s \" \n ", fileName );
  27. }
  28. }
  29.  
  30. public void openFileDeserialize(){
  31. try{
  32. input = new ObjectInputStream( new FileInputStream( fileName ) );
  33. }
  34. catch( Exception e ){
  35. System.out.printf("there was en error using the File: \" %s \" \n ", fileName );
  36. }
  37. }
  38.  
  39. public void setList( Collection<StudentsRegister> registerList ){
  40. try{
  41. openFileSerialize();
  42. output.writeObject( registerList );
  43.            System.out.println("Datos Guardados");
  44. }
  45.  
  46. catch( Exception e){
  47. System.err.println("Can't write or close the File");
  48. System.exit( 1 );
  49. }
  50. }
  51.  
  52. public Collection<StudentsRegister> getList() throws IOException{
  53. try{
  54. openFileDeserialize();
  55.            while(true){
  56.              temporalList = ( ArrayList<StudentsRegister> ) input.readObject();
  57.              temporalList2.addAll(temporalList);
  58.            }
  59. }
  60.        catch(EOFException endOfFileException){
  61.         input.close();
  62.         return temporalList2;
  63.        }
  64. System.out.println("there was an error reading the file");
  65. System.exit( 1 );
  66. }
  67.      return null;
  68.  
  69. }
  70. }


En línea

4nc3str4l

Desconectado Desconectado

Mensajes: 23



Ver Perfil
Re: al serializar, se sobreescriben los objetos, como puedo solucionarlo?
« Respuesta #1 en: 30 Agosto 2012, 16:20 pm »

El problema reside aqui: ya que cuando haces un addstudents el empieza desde i =0 i va guardando estudiantes en la posicion 0, 1, 2 ,3 ,4 y cuando vuelves a invocar el metodo pues vuelve a 0 y empieza a guardar desde 0,1,2,3,4.... asi que los sobreescribe, Creo que la cuestión sería guardar la variable i para que continue desde donde lo dejo en el primer registro de alumnos.
Código:
public void addStudents(){
System.out.println("Insert the number of Students to add ");
final int TOTAL_STUDENTS = keyboard.nextInt();
register = new StudentsRegister[TOTAL_STUDENTS];
for( int i=0; i < register.length; i++ ){
System.out.printf("%s\n%s", "write the name, surname and the mark of the student.", ":? " );
firstName = keyboard.next();
surname = keyboard.next();
mark = keyboard.nextDouble();
register[i] = new StudentsRegister(firstName, surname, mark );
                studentList.add(register[i]);
}
            working.setList( studentList );
}


En línea

# "Saber romper medidas de seguridad no hacen que seas hacker, al igual que saber hacer un puente en un coche no te convierte en un ingeniero de automoción"
-- Eric Raymond
4nc3str4l

Desconectado Desconectado

Mensajes: 23



Ver Perfil
Re: al serializar, se sobreescriben los objetos, como puedo solucionarlo?
« Respuesta #2 en: 30 Agosto 2012, 16:50 pm »

Mira yo haria la siguiente modificacion en el addstudents para guardar una variable contador para que no me sobreescriba los estudiantes:

Código:
public void addStudents(){
System.out.println("Insert the number of Students to add ");
final int TOTAL_STUDENTS = keyboard.nextInt();
register = new StudentsRegister[TOTAL_STUDENTS];
                        //creamos un contador
                        int cont=0;
                        //Nuestro contador ira mirando que posiciones de la array estan llenas para que el for no sobreescriba.
                        while(register[cont]!=null){
                            cont++;
                        }
                        //El for empezará desde donde le ha marcado el contador asi no sobreescribirá
for( int i=cont; i < register.length; i++ ){
System.out.printf("%s\n%s", "write the name, surname and the mark of the student.", ":? " );
firstName = keyboard.next();
surname = keyboard.next();
mark = keyboard.nextDouble();
register[i] = new StudentsRegister(firstName, surname, mark );
                studentList.add(register[i]);
}
            working.setList( studentList );
}

Creo que con eso ya esta listo tu problema. ;)
En línea

# "Saber romper medidas de seguridad no hacen que seas hacker, al igual que saber hacer un puente en un coche no te convierte en un ingeniero de automoción"
-- Eric Raymond
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines