| | |
Modifying a file.
Thread Solved |
•
•
Join Date: May 2008
Posts: 6
Reputation:
Solved Threads: 0
I need to make a seating reservation system for my assignment and I have to manage .dat files. I have to store all Student objects in a file. When a student is registered, a new object is created and I need to add it to the archive. But as far as I know, you can not edit a serializable file in a "direct" form, so what I am trying to do is to generate an array of objects (temporary) with all the objects from the file, enter the new object registered and copy each object from the array to the file again.
I have the methods to do that but I don't know where to call the methods to perform the operations. Also I don't know in which class do I have to create the ArrayList.
Here is my code, I just put the classes relevant to my question:
I translated from Spanish to English some parts of the code so you understand it with more precision.
Thanks for the help in advance.
I have the methods to do that but I don't know where to call the methods to perform the operations. Also I don't know in which class do I have to create the ArrayList.
Here is my code, I just put the classes relevant to my question:
java Syntax (Toggle Plain Text)
import java.io.*; import java.util.*; class Estudiante extends Persona implements Serializable { private String idNo; private byte gradEst; private String codeSeat; public Estudiante(String name, char sex, int age, String location, String idNo, byte gradEst, String codeSeat){ super(name, sex, age, location); setIdNo(idNo); setGrade(gradEst); setCodeSeat(codeSeat); } public void setIdNo(String idNo){ this.idNo=idNo; } public void setGrade(byte gradEst){ this.gradEst=gradEst; } public void setCodeSeat(String codeSeat){ this.codeSeat=codeSeat; } public String getIdNo(){ return idNo; } public byte getGrado(){ return gradEst; } public byte getCodeSeat(){ return codeSeat; } public static ArrayList<Student> generateBackup(){ FileInputStream f3 = null; ObjectInputStream f4 = null; ArrayList<Student> students = new ArrayList<Student>(); try{ f3=new FileInputStream("C:\\Documents and Settings\\Daniel Garcia\\Escritorio\\Andres\\Final\\students.dat"); f4=new ObjectInputStream(f3); while(true){ Student e=(Student)f4.readObject(); students.add(e); } } catch(EOFException e){ System.out.println("End of file"); } catch(IOException e){ System.out.println("Error reading file"); } catch(ClassNotFoundException e){ System.out.println("Error in type of class"); } finally{ try{ f4.close(); f3.close(); } catch(IOException e){ System.out.println("Error closing file"); } } return students; } public static void writeBackup(ArrayList<Student> students){ FileOutputStream f1 = null; ObjectOutputStream f2 = null; try{ f1=new FileOutputStream("C:\\Documents and Settings\\Daniel Garcia\\Escritorio\\Andres\\Final\\students.dat"); f2=new ObjectOutputStream(f1); for(Student e : students){ f2.writeObject(e); } } catch(IOException e){ System.out.println ("Error saving file"); } finally{ try{ f2.close(); f1.close(); } catch(IOException e){System.out.println ("Error closing file"); } } } }
java Syntax (Toggle Plain Text)
import java.io.*; import java.util.*; class Main{ public static void main (String args[]){ boolean menu = false; Student x = null; do{ System.out.println("Welcome!!"); System.out.println(); System.out.println("What do you want to do?"); System.out.println("1) Separate a seat"); System.out.println("2) Cancel a seat"); System.out.println("3) Another here"); System.out.println("4) Another here"); System.out.println("5) Another here"); System.out.println(); char ans = Lectura.readChar(); System.out.println(); switch(ans){ case '1': Student.generateBackup(); System.out.println("Name"); String name = Lectura.readString(); System.out.println("Age"); byte age = Lectura.readByte(); System.out.println("Sex M/F"); char sex = Lectura.readChar(); System.out.println("Id. No."); String idNo = Lectura.readString(); System.out.println("Grade of Studies"); byte gradEst = Lectura.readByte(); System.out.println("Location"); String location = Lectura.readString(); System.out.println("Here is a Seating chart"); Seatings.displaySeatings(); System.out.println("Select your seat"); String codeSeat = Lectura.readString(); x = new Estudiante(name,sex,age,location,idNo,gradEst,codeSeat); //I need to put x in the arraylist but I don't know how to do that, any ideas?? Estudiante.writeBackup(); menu=true; break; } } while(menu); } }
I translated from Spanish to English some parts of the code so you understand it with more precision.
Thanks for the help in advance.
•
•
Join Date: Sep 2008
Posts: 1,566
Reputation:
Solved Threads: 196
Making a class serializable in java means that you can read it from and write it to a file in binary form. So when your program exits, that is when you should be writing all of your objects to the file. When your program starts, you read them in from the file. When you read from a "serializable file", it creates your Objects for you. When you write to a "serializable file" you are essentially storing your Objects in a special form so that they can be read back in, as Objects, when you start your program the next time. I don't know a whole lot about the details of how it works (for example, I'm not sure when or how exactly the Objects are created), but that's the general idea. Hope that helps. If not, and you were already aware of that, I'll be glad to help you work out the details once you reply.
Last edited by BestJewSinceJC; Nov 22nd, 2008 at 4:51 am.
•
•
Join Date: May 2008
Posts: 6
Reputation:
Solved Threads: 0
Yes I understand the mechanism about writing/reading objects from a file. But basically this is my problem:
- I have a file that has objects in it.
- I want to write a new object in that file when I run the program, but if I do that "directly" using the writeObject, then the other objects will be lost (overwriting file).
- So what I am doing is copying every object from the file to an array of objects, so there will no lost objects after writing the new one. Then I copy each object from the array to the file. I have the methods to do that (as you can see in my Estudiante class) but I don't know how to call the methods in Main class to perform this actions.
Estudiante.generateBackup(); >> this line is working OK (line 23)
Estudiante.writeBackup(); >> this is causing an error when I compile (line 44):
ERROR: Main.java:51: writeBackup(java.util.ArrayList<Student>) in Estudiante cannot be applied to ()
Estudiante.writeBackup();
Thanks for your reply.
- I have a file that has objects in it.
- I want to write a new object in that file when I run the program, but if I do that "directly" using the writeObject, then the other objects will be lost (overwriting file).
- So what I am doing is copying every object from the file to an array of objects, so there will no lost objects after writing the new one. Then I copy each object from the array to the file. I have the methods to do that (as you can see in my Estudiante class) but I don't know how to call the methods in Main class to perform this actions.
Estudiante.generateBackup(); >> this line is working OK (line 23)
Estudiante.writeBackup(); >> this is causing an error when I compile (line 44):
ERROR: Main.java:51: writeBackup(java.util.ArrayList<Student>) in Estudiante cannot be applied to ()
Estudiante.writeBackup();
Thanks for your reply.
Last edited by xandres; Nov 22nd, 2008 at 5:15 am.
Just a thought, instead of writing each object after serializing one by one to the file, why don't you just serialize the entire ArrayList and write it to a file.
And when you need to add any data to the file, get the ArrayList back from the file, add the object to the ArrayList and serialize this ArrayList overwrite the older file with the file containing the new ArrayList
And when you need to add any data to the file, get the ArrayList back from the file, add the object to the ArrayList and serialize this ArrayList overwrite the older file with the file containing the new ArrayList
Last edited by stephen84s; Nov 22nd, 2008 at 7:57 am.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."
"How to ask questions the smart way ?"
"How to ask questions the smart way ?"
•
•
•
•
Just a thought, instead of writing each object after serializing one by one to the file, why don't you just serialize the entire ArrayList and write it to a file.
And when you need to add any data to the file, get the ArrayList back from the file, add the object to the ArrayList and serialize this ArrayList overwrite the file with the older file.
java Syntax (Toggle Plain Text)
//... necessary imports public class ArrayList<T> extends List<T> implements Collection<T>, Serializable{ private transient Object[] elements = null; // key point @_@ public T get(int position){ return (T)elements[position]; } }
I felt a bump was in order for this one...
> Unfortunately, the implementation of ArrayList<T> looks
> [something] like this--
Doesn't seem unfortunate to me; as long as the state is persisted and can be recovered from the flattened representation of the object, it doesn't matter which approach is taken to serialize the object. In this case, the implementer chose not to serialize the array which backs the
The only thing you need to look out for is that the objects contained in the
If my memory serves me right, you posted something along the same lines in a thread you created; maybe it's time to go back and edit it. :-)
> Unfortunately, the implementation of ArrayList<T> looks
> [something] like this--
Doesn't seem unfortunate to me; as long as the state is persisted and can be recovered from the flattened representation of the object, it doesn't matter which approach is taken to serialize the object. In this case, the implementer chose not to serialize the array which backs the
ArrayList but the individual elements for obvious reasons [hint: the size of the array is not always equal to the number of elements in the ArrayList ].The only thing you need to look out for is that the objects contained in the
ArrayList can be serialized [the concrete class implements either Serializable or Externalizable ].If my memory serves me right, you posted something along the same lines in a thread you created; maybe it's time to go back and edit it. :-)
I don't accept change; I don't deserve to live.
![]() |
Similar Threads
- File type help (Computer Science)
- assignment help [fstream, on modifying a record in a file] (C++)
- Modifying a project in python (Python)
- Modifying head tag of parent file. (C#)
- Saving a file using C++ (C++)
- modifying an exe (C)
- Modifying pagefile.sys ? (Windows NT / 2000 / XP)
Other Threads in the Java Forum
- Previous Thread: Text modifier program
- Next Thread: Reading in a text file -- efficiently
| Thread Tools | Search this Thread |
6 @param actuate android api applet application arc array arrays automation balls binary bluetooth bold business byte c++ chat class client code codesnippet collections compare component coordinates database defaultmethod doctype dragging ebook eclipse educational error file fractal froglogic game givemetehcodez graphics gui guitesting helpwithhomework hql html ide ideas image ingres input integer internet intersect invokingapacheantprogrammatically j2me java java.xls javaexcel javaprojects jni jpanel jtextarea julia linux list map method methods mobile mysql netbeans newbie nextline parameter php pong problem program programming project recursion recursive rim scanner sell server set sms sort sql string sun swing swt threads tree web websites windows






