vector - multiple entries
Hello.
I'm writing data to a file but i can't figure out how to add multiple entries. Every time i make a new entry the old data is wiped out.
Write vector example:
Vector vector =new Vector();
vector.add("element 1");
vector.add("element 2");
try{
FileOutputStream fout =new FileOutputStream("data.dat");
ObjectOutputStream oos =new ObjectOutputStream(fout);
oos.writeObject(vector);
oos.close();
}catch (Exception e){
e.printStackTrace();
}
Read vector:
Vector vector =new Vector();
try{
FileInputStream fin =new FileInputStream("data.dat");
ObjectInputStream ois =new ObjectInputStream(fin);
vector = (Vector) ois.readObject();
ois.close();
}catch (Exception e){
e.printStackTrace();
}
[1491 byte] By [
johnp11a] at [2007-11-26 18:13:37]

# 2
FileOutputStream fout = new FileOutputStream("data.dat");
This creates a new file every time.
Did you mean to append to the file? In which case that won't work for another reason ... You would have to read the file in as a Vector as per your code, add to the vector, then write it out again to a new file as above.
ejpa at 2007-7-9 5:46:46 >

# 3
I realize my sample code compiles, but thats not my problem. And yes, I suppose I'm trying to append to the file. Anyways, I'll try converting it into an array with the toArray() method.
# 5
I've since found out that the FileOutputStream contains a boolean for appending files.
FileOutputStream("data.dat",true)
I can see that it appends to the file but it only extracts only one row, the first row, and ignores the rest. I tried using the iterator but it does not seem to work so far..
# 11
I'd go like this. Read the Vector from a FileInputStream and ObjectInputStream (on a FileNotFoundException only, create a new Vector). Add the new elements to the Vector. Write the Vector back using a FileOutputStream and ObjectOutputStream, thus overwriting the old Vector, as you've seen already. Is there more to it than this?
Message was edited by:
OleVV
# 12
Got it. My order of operations was wrong.
Thanks.
WRITE
try {
FileOutputStream fout = new FileOutputStream("vector.dat");
ObjectOutputStream oos = new ObjectOutputStream(fout);
vector.add("element1");
oos.writeObject(vector);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
READ
try {
FileInputStream fin = new FileInputStream("vector.dat");
ObjectInputStream ois = new ObjectInputStream(fin);
vector = (Vector) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
Message was edited by:
johnp11