0

I use the following code to copy a javax.sound.midi.Sequence :

private Object copyObject(Object objSource)
{
  Object objDest=null;

  try
  {
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    ObjectOutputStream oos=new ObjectOutputStream(bos);
    oos.writeObject(objSource);
    oos.flush();
    oos.close();
    bos.close();
    byte[] byteData=bos.toByteArray();
    ByteArrayInputStream bais=new ByteArrayInputStream(byteData);
    try { objDest=new ObjectInputStream(bais).readObject(); }
    catch (ClassNotFoundException e) { e.printStackTrace(); }
  }
  catch (IOException e) { e.printStackTrace(); }
  return objDest;
}

javax.sound.midi.Sequence sequence;
...
javax.sound.midi.Sequence newSequence=(Sequence)copyObject(sequence);

I got the following error :

java.io.NotSerializableException: javax.sound.midi.Sequence

What's the proper way to do this ?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Frank
  • 30,590
  • 58
  • 161
  • 244
  • 3
    Just avoiding the duplication, I guess this link will be helpful for you https://stackoverflow.com/questions/13895867/java-io-notserializableexception – Ihar Hulevich Apr 12 '19 at 22:38

1 Answers1

2

As the exception indicates, Sequence is not a serializable class, so you cannot serialize it.

Use MidiSystem.write and MidiSystem.getSequence instead of ObjectOutputStream and ObjectInputStream:

if (objSource instanceof Sequence) {
    Sequence sequence = (Sequence) objSource;
    int[] types = MidiSystem.getMidiFileTypes(sequence);

    MidiSystem.write(sequence, types[0], bos);

    byte[] byteData = bos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(byteData);

    try {
        return MidiSystem.getSequence(bais);
    } catch (InvalidMidiDataException e) {
        throw new IOException(e);
    }
}

Another approach would be to create a new Sequence, and copy each of the original Sequence’s Tracks, which would mean copying each Track’s MidiEvents, using cloned MidiMessages.

If you are hoping for a method that can universally copy any object, I’m afraid it simply is not possible. Objects which are not serializable will always require manual copying.

VGR
  • 40,506
  • 4
  • 48
  • 63