简体   繁体   中英

Getting java.io.NotSerializableException error

I want to save an object of

 javafx.scene.media.MediaPlayer 

class using ObjectOutputStream, but it only works with serializable classes and it looks like MediaPlayer class is not serializable.

This is my code:

 ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                new BufferedOutputStream(new FileOutputStream(file)));

        MediaPlayer[] player = songList.toArray(new MediaPlayer[songList.size()]);

        objectOutputStream.writeObject(player); // error occurs here

        objectOutputStream.close();

And I get this error:

java.io.NotSerializableException: javafx.scene.media.MediaPlayer
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeArray(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at mp3.MusicPlayer.saveSongs(MusicPlayer.java:72)
at mp3.MainFrame$1.windowClosing(MainFrame.java:55)

How to solve this problem ?

The best question here is why would you want to save this in the first place. Taking into consideration that MediaPlayer is a JavaFx component I do not see the reason for wanting to serialize and save this.

Assuming that what you want to achieve is to save the songList you're passing in I would just go ahead and do exactly that.

There is no point in serializing and saving objects like a MediaPlayer , just save the list of songs and/or whatever settings. Then in case you can to reconstruct this somewhere else, just deserialize the saved data and reconstruct a new MediaPlayer instance with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM