Reputation:
I am creating a command line interface representing a bookeeping system. I need to use .txt files as an external database.Each book keeping building should be mapped to a list of all the books stored at that location. I want to be able to save each book keeping building object , which is mapped to all of its books, in the txt file and be able to read, update, insert, delete the same txt file even after my application has stopped running and started again.
public static ArrayList<Object> readObjects(){
ArrayList<Object> al = new ArrayList<Object>();
boolean cont = true;
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("outputFile"));
while(cont){
Object obj=null;
try {
obj = ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if(obj != null)
al.add(obj);
else
cont = false;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return al;
my current implementation can only write the objects in the array into a new txt file, but not being able to update/delete when there's already an existing txt file with data from a previous session of the application
Is is even possible to update object object paramters/delete entire objects that are already saved in the txt file or would i have to reinstatiated the objects from the txt file, delete everything from said txt file, do whatever updates i need to do with the objects previously extracted, then finally write the objects(and or new objects), back into the txt file? Thanks everyone!
Upvotes: 1
Views: 1772
Reputation: 7232
A few comments here, with the caveat that I have not worked with directly serializing objects to a file for awhile.
RandomAccessFile
. Deletion of records is then accomplished by marking them as deleted (not actually removing them from the file) and having compaction operations that will ultimately remove them when writing the data to a new file when necessary / triggered.RandomAccessFile
but could be a performance issue for large data sets (100s of MB to GB etc).Lastly, these problems have already been solved for you if you use a database system (many options).
Upvotes: 0
Reputation: 3180
There are a few ways to do this:
Load file into memory at the beginning of each operation, then save at end
Load file into memory at start of application, operate in memory, save to file when application closed
Save each book object in a file, with a key (book id? name?) as the filename.
Just a few options for you to consider.
Upvotes: 2