How to write a file using ObjectOutputStream?

97
April 24, 2019, at 7:20 PM

I'm trying to write to a file and have now narrowed the problem down to the writeObject() method.

It is not writing the data to the file.

When i run oos.writeObject(siteData), nothing happens. The file remains empty

As you can see in the following code i have put in some System.out.println()s and they all return a full list

I have also been looking at it in the debugger step by step and it is not being overwritten later in the program.

I have also made sure that SiteData implements Serializable

What can cause this problem?

public void saveToStorageFile() throws IOException {
       System.out.println("saveToStorageStart() started!");
       FileOutputStream fos = new FileOutputStream(new File("SiteDataStorage"));
       ObjectOutputStream oos = new ObjectOutputStream(fos);
       //Prints the List
       for(int i = 0 ; i < this.size(); i++) {
           System.out.println("Save list:" + this.db.get(i).getText());
       }
       SiteData[] siteData = db.toArray(new SiteData[db.size()]);
       //Prints the sitedata array length
       System.out.println(siteData.length);
       oos.writeObject(siteData);
       oos.close();
       System.out.println("Saved!");
   }

Thanks!

Answer 1

I've added this to make it a complete example.

import java.io.*;
import java.util.*;
class SiteData implements Serializable {
    public static void main(String[] args) throws Throwable {
        new SiteData().saveToStorageFile();
    }
    private int size() { return 1; } // Did you not want db?
    private List<SiteData> db = List.of(this);
    private String getText() { return "Some text"; }

And appended the } to close the class.

Works for me!

READ ALSO
Alternating Sort, Array out of bounds problem [duplicate]

Alternating Sort, Array out of bounds problem [duplicate]

This question already has an answer here:

110
How to get out of an &ldquo;if&rdquo; statement that is being constantly updated in java

How to get out of an “if” statement that is being constantly updated in java

I am trying to break out of an "if" statement that is constantly being checked

121
How to add JTextField Value to String array using a button

How to add JTextField Value to String array using a button

I need to add the text that is typed into a JTextField to a string array String[] by using a JButtonFor example, if I type into a JTextField, I would click a JButton which would add that text into a String[]

106
Sharing a file with Android Intent: File extension is removed

Sharing a file with Android Intent: File extension is removed

I'm using the following code to share an audio file with Android Studio 33

72