Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Problems with an Object File

  1. #1
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Unhappy Problems with an Object File

    Hi, i must do an "agenda" that is the file, you can choose with the programm. (i don't know how to do it like Norm told me with Files. to test "new StringReader("example"); with file of objects...)

    What i must do:


    case INCLUSION: For write an object into the file (filled attributes) <-- DONE
    case BUSQUEDA: For search a "Alumno16.telefono" with a name.
    <-- DONE

    case CONSLUTA: must show count of objects that has the file. <- don't know how
    case LECTURA: must show an Object with the index that user specify. <- don't know how


    case CONSULTAR: read all objects in the "agenda" <-- DONE


    case ACTUALIZAR: update an Object from the file. (replace it) <-- I found a method replace on ObjectOutputStream but it is protected and don't know what it means,

    case BORRAR: delete an object from the file. <-- don't know how.


    import java.io.*;
    import java.util.Scanner;
     
    public class ArchivoObjetos {
     
    	static Scanner sc = new Scanner(System.in);
     
    	static final int LINEAS = 1;
     
    	static final char INCLUSION = 'a';
    	static final char BUSQUEDA = 'b';
    	static final char CONSULTA = 'c';
    	static final char LECTURA = 'd';
    	static final char CONSULTAR = 'e';
    	static final char ACTUALIZAR = 'f';
    	static final char BORRAR = 'g';
     
    	static final char SALIR = 's';
     
    	public static void main(String[] args) {
     
    		try{
    			BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
    			char opcion;
    			String fichero;
     
    			//Control para que exista el fichero
    			do{
    				//Fuera de los dos do-while. para trabajar en el mismo fichero durante toda la ejecución del programa.
    				System.out.println("Introduzca el nombre del fichero de alumnado que desea manejar:");
    				fichero = lector.readLine();
    				if(!(new File(fichero).exists()))
    					System.err.println("El fichero no existe, vuelva a intentarlo.");
    			}while(!(new File(fichero).exists()));
     
     
    			//Control de la salida del menú
    			do{
    				ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fichero, true));
    				ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fichero));
    				MiObjectOutputStream moos = new MiObjectOutputStream(new FileOutputStream(fichero, true));
    				Alumno16 alum = new Alumno16();
     
    				opcion=menu();
     
    				switch(opcion){	
    					case INCLUSION:
    						System.out.println("Introduzca el nombre del alumno:");
    						alum.nombre = lector.readLine();
    						System.out.println("Introduzca el telefono del alumno:");
    						alum.telefono = Integer.parseInt(lector.readLine());
    						System.out.println(fichero.length());
    //trying to count objects
    						alum.numEntradas += 1;
    						if(fichero.length()==0)//i create new file with 0, but when it come here. it lenght is = 9
    							//object with header, for first time on writing. Doesnt work
    							oos.writeObject(alum);
    						else{
    							//my object without header,
    							moos.writeObject(alum);
    						}
    						break;
    					case BUSQUEDA:{
    						Alumno16 a;
    						System.out.println("Introduzca el nick identificador del alumno, para encontrar su teléfono.");
    						String nombre = lector.readLine();
    						boolean finFichero = false;
     
    						while(!finFichero){
    							try{
    								a = (Alumno16) ois.readObject();
    								if(a.nombre.equals(nombre))
    									System.out.println("El número de teléfono del alumno "+a.nombre+" es: "+a.telefono);
    							}catch(EOFException e){
    								finFichero = true;
    							}
    						}
    						break;
    					}
    					case CONSULTA:
    						System.out.println("El número de entradas es de:");
    						break;
    					case LECTURA:
    						break;
    					case CONSULTAR:
    						break;
    					case ACTUALIZAR:
    						break;
    					case BORRAR:{
    						Alumno16 a;
    						System.out.println("Introduzca el nombre del alumno que desea borrar:");
    						String nombre = lector.readLine();
    						boolean finFichero = false;
    						while(!finFichero){
    							try{
    								a = (Alumno16) ois.readObject();
    								if(a.nombre.equals(nombre)){
     
    								}
    							}catch(EOFException e){
    								finFichero = true;
    							}
    						}
    						break;
    					}
    					case SALIR:
    						System.out.println("Finalización normal del programa.");
    				}
    				//Por cada operación realizada, se vuelcan los datos de la memoria al disco.
    				oos.close();
    				moos.close();
    				ois.close();
    			}while(opcion != SALIR);
     
    		}catch(NumberFormatException e){
    			System.err.println("Error. Se esperaba un número.");
    		}catch(FileNotFoundException e){
    			System.err.println("Archivo no encontrado.");
    		}catch(IOException e){
    			System.err.println("Error de lectura / escritura.");
     
    		}catch(Exception e){
    			System.err.println("Se ha producido un error.");
    		}
    	}
    	static char menu(){
    		limpia();
    		System.out.println(INCLUSION+". Inclusión de una nueva entrada en la agenda(nuevo alumno).");
    		System.out.println(BUSQUEDA+". Búsqueda de un número de teléfono a partir del login de un usuario.");
    		System.out.println(CONSULTA+". Consulta del número de entradas de la agenda.");
    		System.out.println(LECTURA+". Lectura de una entrada concreta a partir de la posición que ocupa.");
    		System.out.println(CONSULTAR+". Consultar todas las entradas de la agenda.");
    		System.out.println(ACTUALIZAR+". Actualizar datos de un alumno.");
    		System.out.println(BORRAR+". Borrar  un alumno de la agenda.");
    		System.out.println(SALIR+". Salir.");
    		return sc.next().charAt(0);
    	}
    	static void limpia (){
    		for(int i=0; i<LINEAS ;i++)
    			System.out.println();
    	}
    }
    class MiObjectOutputStream extends ObjectOutputStream{
     
    	public MiObjectOutputStream(OutputStream out) throws IOException {
    		super(out);
    	}
    	protected MiObjectOutputStream() throws IOException, SecurityException {
    		super();
    	}
    	//Método heredado de ObjectOutputStream sobreescrito en blanco
    	public void writeStreamHeader() throws IOException{
     
    	}
    }
    class Alumno16 implements Serializable{
     
    	public static final long serialVersionUID = 1;
     
    	int numEntradas;
    	String nombre;
    	int telefono;
    	//int curso;
    	//char letra;
    }


    --- Update ---

    I noticed that "case INCLUSION" for add objects, doesn't make a header because its length is never 0. It is 4 bytes before write anything , why?

    and if i try this, it isn't true neither, because if i do System.out.println(fichero.length()), and it says: 9
    if(fichero.length()==4)
        oos.writeObject(alum);

    edited : added some coments

    After search all over the internet with all keywords possible, i don't find a way to solve my problems. I read all API methods of OOS and OIS , and not understood / found any useful...

    Thank you in advance


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Problems with an Object File

    What keys does the user press on the keyboard to test this program, including the Enter key?
    The program asks for user input. What is that input?
    Given all the user input, a StringReader object can be created that automatically provides answers to the questions asked by the program.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Convert File Object to class<?> object
    By CEO in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: June 27th, 2012, 06:55 PM
  2. Charset problems when altering a pdf-file
    By jakobmann in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: May 7th, 2012, 05:02 AM
  3. Im having problems compiling a very simple .js file to .exe
    By idesyl in forum Member Introductions
    Replies: 3
    Last Post: March 10th, 2011, 05:16 AM
  4. insert(embed) a file object (.txt file) in MS excel sheet using java.
    By jyoti.dce in forum What's Wrong With My Code?
    Replies: 1
    Last Post: August 12th, 2010, 08:16 AM
  5. Problems with File Reader (Strings and 2D Array Storage)
    By K0209 in forum File I/O & Other I/O Streams
    Replies: 44
    Last Post: January 12th, 2010, 10:48 AM