0

I would like to be able to allow the user to create an object by inputing its information and pressing a button, without first instantiating the object in the code.

I am using serialization to save an object with data inputted by the user in a bi file, but every time I try to save a new object, it overwrites it

public void addMovie2() throws IOException {
        MoviesLinkedList.add(new Movies (textField.getText(), ratings.getSelectedItem(), textField_1.getText()));

        Movies movie1 = new Movies(textField.getText(), ratings.getSelectedItem(), textField_1.getText()); 

        String Filename = "MoviesLinkedList.bin";

        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(Filename));
        os.writeObject(movie1);
        os.close();

        System.out.println("Done Saving");
}

I run this method whenever the user presses an "Add" button. This works for 1 move object, whenever I want to save more than one, it overwrites it.

Here is the code I wrote to read the object in a JTextArea:

 String Filename = "MoviesLinkedList.bin";
          try {
            ObjectInputStream is = new ObjectInputStream(new FileInputStream(Filename));
             Movies movie1 = (Movies) is.readObject();
             MoviesTextArea.setText("Title: " + movie1.title + "    Rating: " + movie1.rating + "    Review: " + movie1.review);
             is.close();
          } catch (IOException e1) {
            e1.printStackTrace();
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }

            }
Tommy
  • 3
  • 3
  • why don't put constructo of new Mobies into writeObject like `os.writeObject(new Movies(textFields.getText()...))` ? – Dred Apr 03 '19 at 14:23
  • 1
    It seems that you always use the the same `Filename` (MoviesLinkedList.bin) for the output stream. At least from the code that you posted... – Vall0n Apr 03 '19 at 14:24
  • Yes, the filename should be the same (?) – Tommy Apr 03 '19 at 14:36
  • In your updated question you read the first object only. Clearly you just don't continue to read other objects – igorepst Apr 03 '19 at 14:54
  • @igorepst yes I know. I don't know how to read the objects the user creates as I don't know their name. – Tommy Apr 03 '19 at 14:55
  • [Please see this](https://stackoverflow.com/questions/27409718/java-reading-multiple-objects-from-a-file-as-they-were-in-an-array) However, I think you should accept the given answer, as you asked how not to overwrite the file – igorepst Apr 03 '19 at 14:57
  • @Tommy - You can read objects in the sequence they were written, by calling `ObjectInputStream.readObject()`. You can use any variable name you like to point to the object read. – Andy Thomas Apr 03 '19 at 15:30
  • @igorepst should i ask another question? – Tommy Apr 03 '19 at 17:18
  • @AndyThomas I use the readObject method, the problem is that I don't know the variable name – Tommy Apr 03 '19 at 17:19
  • Yes, but please pay attention that this should not be some kind of a chat. Please describe exactly what would you like to get when parsing the file, e.g. do you want each time to read all what was written inside (e.g. in loop), or do you use the file as some kind of a message buffer and want to read only first/last/specific value. The question should include the code to read and write the file also. In addition, @AndyThomas gave you a hint, however your answer is not clear at all. What variable name do you refer to? – igorepst Apr 03 '19 at 17:23
  • @Tommy - you can make up any variable name you like to point to the object you've read. It doesn't have to have the same name as the variable used when *writing* the object. The variable name is not the name of an object. It's just a name of one of possibly multiple variables that *point* to the object. – Andy Thomas Apr 03 '19 at 17:24
  • @igorepst What I am trying to do is a program that allows the user to add "movie objects" with a title, a rating, and a review. I want the user to be allowed to create as many objects he wants and I want to save them in a file and show them in a textarea. This is in a few words what I want to do with the objects. – Tommy Apr 03 '19 at 18:03
  • @AndyThomas please refer to my above comment – Tommy Apr 03 '19 at 18:03
  • @Tommy, this is pretty much understandable from the context of the question. However, what should be done when the user adds a movie? Should the textarea be updated immediately? If yes, it may be updated directly without reading from the file, I imagine. Also you may possibly use [FileWriter to write text and not binary](https://stackoverflow.com/questions/1225146/java-filewriter-with-append-mode) – igorepst Apr 03 '19 at 18:11

2 Answers2

0

One of the FileOutputStream constructors has a parameter append. Hence just use

ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(Filename, true));

Code to test:

public static void main(String[] args) throws IOException {
       f("first");
       f("second");
       f("third");
    }


private static void f(Object o) throws IOException {
        String Filename = "MoviesLinkedList.bin";
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(Filename, true));
        os.writeObject(0);
        os.close();
    }
igorepst
  • 1,230
  • 1
  • 12
  • 20
  • 1
    I tried that already but it doesn't seem to work... It doesn't overwrite my previously saved one but it just doesn't save the new one. – Tommy Apr 03 '19 at 14:35
  • 1
    @Tommy - How do you know it doesn't append the new serialization? Does the file size change? – Andy Thomas Apr 03 '19 at 14:43
  • Please see the code to test, the file is updated properly. Perhaps the code you wrote for reading doesn't work. Just check the size of the file – igorepst Apr 03 '19 at 14:46
  • @igorepst I will try it. I updated my question with the code I wrote to read the objects. – Tommy Apr 03 '19 at 14:48
  • If you wish to post the reading code, please update the question in the first place, clearly stating what the issue is. As of now, you asked how not to overwrite the file – igorepst Apr 03 '19 at 14:50
  • @Tommy - Check the file size. You may actually be appending a new serialization to the file. The actual issue might be that you're using multiple ObjectOutputStream objects to write to one file. Each of those writes a serialization stream header. Try using exactly one ObjectOutputStream for all objects written – Andy Thomas Apr 03 '19 at 14:53
0

Use a single ObjectOutputStream to write multiple objects to a single file, if you intend to read them with a single ObjectInputStream.

The serialized file does not consist just of a sequence of serialized objects. Each ObjectOutputStream writes a serialization header to the stream before any sequence of objects or primitives you write. Using append mode with multiple FileOutputStreams won't help you.

It's possible to use multiple ObjectOutputStream's for a single file, if you also use multiple ObjectInputStream's. In this case, you might also need to seek to a particular position in the file.

By the way, Java provides a convenient mechanism to ensure that a stream is closed -- even if an exception occurs. The try-with-resources block also requires less code.

try ( ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(Filename))) {
    os.writeObject(movie1);
}
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151