0

the given function writes in file but on calling again it overwrites the previous list object in file eg

if array list index 0 contain name- "aman" and i call this function it saves "aman" in file. but when for index 1 having name-"lavesh" is called it overwrites on previous data

it is in file like "lavesh" but i want it like " aman lavesh "

public void alter_file( ArrayList<Flight_registrie> x) {
    try {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(" Flight Registrie.txt"));
            oos.writeObject(x);
            x.clear();
            oos.close();
    } catch (IOException e) {
        System.out.println("An I/O error occurs");
        e.printStackTrace();
    }   
}

No error is there but my method can be wrong

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Aman Verma
  • 21
  • 1
  • 6
  • I'm no expert in this, but you are not writing to a text file but rather are serializing to a data file. In this situation, it may be better to re-serialize the whole data rather than trying to append to an existing file. Appending works great for a text file, and one way to do this is to use a FileWriter whose second boolean parameter is `true`, but again, that is not what we're talking about here... although FileOutputStream also can take a second boolean parameter that determines if you append or not. Again I'm not sure how safe this is – Hovercraft Full Of Eels Oct 20 '19 at 19:46
  • 1
    Possible duplicate of [How to write data with FileOutputStream without losing old data?](https://stackoverflow.com/questions/8544771/how-to-write-data-with-fileoutputstream-without-losing-old-data) – Hovercraft Full Of Eels Oct 20 '19 at 19:48
  • thanks for sharing the other question i have same issue – Aman Verma Oct 20 '19 at 20:26
  • Then fix it as per the answer in the duplicate – Hovercraft Full Of Eels Oct 20 '19 at 20:27
  • 1
    Make sure the **Flight_registrie** class **implements Serializable**. then so as to ***append*** to the file: `ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(" Flight Registrie.txt", true));`. – DevilsHnd - 退職した Oct 20 '19 at 21:41

1 Answers1

0

Yes oos.writeObject(x); will write a file with the content of x. It will remove the content of the old file then.

You can simply avoid this by adding true behind the constructor of FileOutputStream. The boolean decides whether you want to append to the file or not. Default is that you don't want to append data.

Doompickaxe
  • 194
  • 1
  • 9