Foro de elhacker.net

Programación => Java => Mensaje iniciado por: Toryas en 30 Octubre 2007, 04:50 am



Título: ayuda con lectura y escritura de datos.ser
Publicado por: Toryas en 30 Octubre 2007, 04:50 am
hola les cuento la cosa es que quiero guardad los datos de mi progreama en archivos serializables y cosa que al salir del programa guarde los datos y al iniciar el programa cargue los datos pero  teno un problemita la cosa esque al compilar todo bn

peor el problema e sque cuendo lo corro s eme cae el programa aver si le pueden echar un ojo a la cosa plz

aki van los codigos

ojo el error lo puse alfinal puede que se amejor leer el error primero

Código
  1. import java.io.*;
  2. public class Taller{
  3. public static Listas listas = new Listas();
  4. public static BufferedReader teclado = new BufferedReader (new InputStreamReader(System.in));
  5. public static Taller obj = new Taller();
  6. public static byte opc = 0;
  7. public static byte opc2 = 0;
  8. public static Cliente client;
  9. public static String vrut;
  10.  
  11.  
  12. public static void main(String[] args) throws IOException,ClassNotFoundException{
  13. listas.leerDatos();
  14. obj.menu();
  15.  
  16. }
  17.  
  18. public void menu()throws IOException{//menu principal
  19. System.out.println( "\t\t\t\t  MENU PRINCIPAL\n\n");
  20.        System.out.println( "\t\t\t 1.-  Ingresar Cliente\n");//listo
  21.        System.out.println( "\t\t\t 2.-  Agregar Cliente\n ");//listo
  22.        System.out.println( "\t\t\t 3.-  Salir \n ");//listo
  23.  
  24.        System.out.print("\nIngrese opcion : ");
  25.        try {
  26.  
  27.          opc = Byte.parseByte (teclado.readLine());
  28.          }
  29.  
  30.          catch (Exception e) {
  31.  
  32.          System.out.println("\n\nIngrese solo Numeros");
  33.          obj.menu();
  34.        }
  35.  
  36.        switch (opc){
  37.         case 1 : obj.ingresarCliente();
  38.         break;
  39.  
  40.         case 2 :obj.agregarCliente();
  41.         obj.menu();
  42.         break;
  43.  
  44.         case 3 :listas.guarDatos();
  45.         System.exit(0);
  46.         break;
  47.  
  48.         default :System.out.println("\nINGRESE UNA OPCION VALIDA");
  49.              obj.menu();
  50.            break;
  51.     }
  52.     }//fin menu principal
  53.  
  54.    public void menuCliente()throws IOException{ //menu cliente
  55.     System.out.println( "\t\t\t\t  MENU CLIENTE\n\n");
  56.     System.out.println( "\t\t\t 1.-  Modificar Datos\n");
  57.     System.out.println( "\t\t\t 2.-  Agregar Auto\n");//listo
  58.     System.out.println( "\t\t\t 3.-  Reparaciones de autos\n");
  59.     System.out.println( "\t\t\t 4.-  Deuda\n");
  60.     System.out.println( "\t\t\t 6.-  Regresar\n");//listo
  61.     System.out.print("\nIngrese opcion : ");
  62.        try {
  63.  
  64.          opc2 = Byte.parseByte (teclado.readLine());
  65.          }
  66.  
  67.          catch (Exception e) {
  68.  
  69.          System.out.println("\n\nIngrese solo Numeros");
  70.          obj.menuCliente();
  71.        }
  72.  
  73.        switch (opc2){
  74.         case 1 :client.printAut();
  75.         obj.menuCliente();
  76.         break;
  77.  
  78.         case 2 :obj.agrarAudo();
  79.         obj.menuCliente();
  80.         break;
  81.  
  82.         case 3 :obj.agregarCliente();
  83.         break;
  84.  
  85.         case 4 : obj.menuCliente();
  86.         break;
  87.  
  88.         case 5 : obj.menuCliente();
  89.         break;
  90.  
  91.         case 6 : obj.menu();
  92.         break;
  93.  
  94.         default :System.out.println("\nINGRESE UNA OPCION VALIDA");
  95.              obj.menuCliente();
  96.            break;
  97.     }  
  98.  
  99. }//fin Menu Cliente
  100. public void menuRep()throws IOException{//menu Reparaciones
  101. System.out.println( "\t\t\t\t  MENU PRINCIPAL\n\n");
  102.        System.out.println( "\t\t\t 1.-  Agregar Reparacion\n");
  103.        System.out.println( "\t\t\t 2.-  Modificar Reparacion\n ");
  104.        System.out.println( "\t\t\t 3.-  Regresar \n ");//listo
  105.  
  106.        System.out.print("\nIngrese opcion : ");
  107.        try {
  108.  
  109.          opc = Byte.parseByte (teclado.readLine());
  110.          }
  111.  
  112.          catch (Exception e) {
  113.  
  114.          System.out.println("\n\nIngrese solo Numeros");
  115.          obj.menu();
  116.        }
  117.  
  118.        switch (opc){
  119.         case 1 : obj.menuRep();
  120.         break;
  121.  
  122.         case 2 :obj.menuRep();
  123.         break;
  124.  
  125.         case 3 :obj.menuCliente();
  126.         break;
  127.  
  128.         default :System.out.println("\nINGRESE UNA OPCION VALIDA");
  129.              obj.menuRep();
  130.            break;
  131.     }
  132.     }//fin menu Reparaciones
  133.  
  134. //Metodos Menu Principal
  135. public void agregarCliente()throws IOException{
  136.  
  137. String nombre, apellido,direccion,telefono,rut;
  138.  
  139. System.out.println("Ingrese Nombre");
  140. nombre = teclado.readLine();
  141. System.out.println("Ingrese Apellido");
  142. apellido = teclado.readLine();
  143. System.out.println("Ingrese rut");
  144. rut = teclado.readLine();
  145. System.out.println("Ingrese Direccion");
  146. direccion = teclado.readLine();
  147. System.out.println("Ingresar Telefono");
  148. telefono = teclado.readLine();
  149. listas.addCliente(new Cliente(nombre, apellido, rut,telefono, direccion));
  150. }
  151.  
  152. public void ingresarCliente()throws IOException{
  153.  
  154. System.out.println("Ingrese rut de Cliente");
  155. vrut = teclado.readLine();
  156.  
  157. client = listas.buscaCliente(vrut);
  158. if(client != null){
  159. obj.menuCliente();
  160. }
  161. else{
  162. System.out.println("El cliente no existe");
  163. obj.menu();
  164. }
  165. }//Fin menu pricipal
  166.  
  167. //Metosdos menu Cliente
  168.  
  169. public void agrarAudo()throws IOException{
  170.  
  171. String marca,modelo,patente;
  172. int anno;
  173.  
  174. System.out.println("Patente del Auto");
  175. patente = teclado.readLine();
  176. System.out.println("Marca Del Auto");
  177. marca = teclado.readLine();
  178. System.out.println("Modelo Del Auto");
  179. modelo = teclado.readLine();
  180. System.out.println("Año Auto");
  181. anno = Integer.parseInt(teclado.readLine());
  182. client.addAuto(new Auto(patente,marca,modelo,anno));
  183. }
  184.  
  185. //Fin Metodos Menu Cliente
  186. }

este es el metodo de escritura:
Código
  1. import java.io.*;
  2. import java.util.*;
  3. public class Escritura {
  4. private FileOutputStream file;
  5. private ObjectOutputStream output;
  6.  
  7. // Abrir el fichero
  8. public void abrirA() throws IOException {
  9. file = new FileOutputStream( "Datos.ser" );
  10. output = new ObjectOutputStream(file);
  11. }
  12.  
  13. // Cerrar el fichero
  14. public void cerrar() throws IOException {
  15. if (output!=null)
  16. output.close();
  17. }
  18.  
  19. // Escribir en el fichero
  20. public void escribir (ArrayList lista) throws IOException {
  21. if (output!=null)
  22. output.writeObject(lista);
  23. }
  24. }
  25.  
este el de lectura:
Código
  1. import java.util.*;
  2. import java.io.*;
  3. public class Lectura {
  4. private FileInputStream file;
  5. private ObjectInputStream input;
  6.  
  7. public void abrir() throws IOException {
  8. file = new FileInputStream( "Datos.ser" );
  9. input = new ObjectInputStream (file);
  10. }
  11.  
  12. public void cerrar() throws IOException {
  13. if (input!=null )
  14. input.close();
  15. }
  16.  
  17. public ArrayList leer () throws IOException, ClassNotFoundException {
  18. ArrayList lista = null;
  19. if (input!=null) {
  20. try {
  21. lista = (ArrayList) input.readObject();
  22. }
  23. catch (EOFException eof) {
  24. // Fin del fichero
  25. }
  26. }
  27. return lista;
  28. }
  29. }
y esta e sla clase de lo que estoy guardando
Código
  1. import java.io.*;
  2. import java.util.*;
  3. public class Listas implements Serializable {
  4. public Cliente algo;
  5. public static Escritura clientx = new Escritura();
  6. private ArrayList clientes = new ArrayList();
  7. public static Listas lis = new Listas();
  8. private FileOutputStream file;
  9. public Escritura escritura;
  10. public static Lectura lec;
  11.  
  12. public Cliente buscaCliente(String vrut){
  13. int i;
  14. for(i=0;i<clientes.size();i++){
  15. algo =(Cliente)clientes.get(i);
  16.   if(vrut.equals(algo.getRut()) ){
  17.   return algo;
  18.   }  
  19. }
  20. return null;
  21. }
  22.  
  23. public void addCliente(Cliente cliente)throws IOException{
  24. clientes.add(cliente);
  25. }
  26. public void guarDatos()throws IOException{
  27. escritura.abrirA();
  28. escritura.escribir(clientes);
  29. escritura.cerrar();
  30. }
  31. public void leerDatos()throws IOException,ClassNotFoundException{
  32. lec.abrir();
  33. clientes = lec.leer();
  34. lec.cerrar();
  35. }
  36. }

bueno el error que me tira es este:
Código:
--------------------Configuration: <Default>--------------------
Exception in thread "main" java.lang.NullPointerException
    at Listas.leerDatos(Listas.java:32)
    at Taller.main(Taller.java:13)

Process completed.


Título: Re: ayuda con lectura y escritura de datos.ser
Publicado por: darkraider en 30 Octubre 2007, 08:20 am
 Buenas, mira no se si habrás leido el error, pero te tira una NullPointerException, por lo tanto estas intentando acceder a algun metodo de una variable que apunta a null.
 Ahora, la clase que tira el error es la Lectura, pero como estas checkeando que el imput no es null, creo que el problema puede estar en acceder al archivo.
 Intenta usar alguna caja de dialogo del awt.
 Espero ayudarte salu2


Título: Re: ayuda con lectura y escritura de datos.ser
Publicado por: Casidiablo en 30 Octubre 2007, 15:32 pm
No le he echado bien ojo, pero creo que te falta incializar el objeto

public static Lectura lec;

Es decir, lo declaras pero no lo inicializas.... además sería bueno que le colocaras constructores a las clases.

Un saludo!


Título: Re: ayuda con lectura y escritura de datos.ser
Publicado por: Toryas en 31 Octubre 2007, 02:06 am
ya salucione sla cosa er alo que decia casidiablo tenia que inicializar la cosa


Título: Re: ayuda con lectura y escritura de datos.ser
Publicado por: Casidiablo en 31 Octubre 2007, 19:05 pm
Y donde está el código funcionando que no lo pillo?


Título: Re: ayuda con lectura y escritura de datos.ser
Publicado por: Toryas en 1 Noviembre 2007, 04:40 am
antes de subir el codigo corregido, quisiera arreglar otro problemita esque cuando el fichero no existe el que contiene los datos a cargar la aplicaiocne este s eme cuelga  y no se como hacer que no s eme caiga no se ocmo ocupar el java.io.FileNotFoundException


Título: Re: ayuda con lectura y escritura de datos.ser
Publicado por: Casidiablo en 2 Noviembre 2007, 16:29 pm
Hay funciones para saber si el archivo existe o no.... lamento no recordar mis clases de Java, pero creo que era algo como fileExist(), o algo así. Busca un poco en el google. Aunque estoy seguro de que hay ejemplos en el post con chincheta de este subforo.

Un saludo!


Título: Re: ayuda con lectura y escritura de datos.ser
Publicado por: marioly en 3 Noviembre 2007, 15:32 pm
Hay metodos, como exists() de file, puedes verificar con eso. O manejar la excepcion