0

I have the following arrayList

import java.io.*;
import java.util.*;
import java.util.logging.*;

public class SaveData{
int counter =1;
public void saveTheData(ArrayList<myClass> myClassObj){
    try{
        FileOutputStream fout = new FileOutputStream(counter+"SaveGame.ser", true);
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(myClassObj.toString() );
        counter++;
        oos.close();
    } catch (Exception e) {
        e.printStackTrace();
    } 
}
}

Sorry I'm new to java so plese excuse any silly questions. The code above saves the array in ser format. I need to save it in binary format and then be able to also read it from its binary format later. I have no idea how you do this though

Any help is much appreciated

  • 3
    You probably don't want to write the `toString()` representation of your object to disk, but you want to *serialize* the object in binary format into a stream / file. Your `myClass` class must then implement the `Serializable` interface (`ArrayList` is already serializable), then you can call `oos.writeObject(myClassObj);`. I think it'd be best if you start reading up on serialization and deserialization, e.g. on http://www.javacoffeebreak.com/articles/serialization/index.html . – Maximilian Gerhardt Jan 02 '16 at 22:33

2 Answers2

1

As stated by others, if you want to write binary, don't use the toString() method when serializing the object. You also need to implement Serializable in class myClass. Then deserializing is just as simple as serializing, by using ObjectInputStream.readObject().

Your resulting SaveData class should then look something like this:

import java.io.*;
import java.util.*;

public class SaveData {
    int counter = 1;

    public void saveTheData(ArrayList<myClass> myClassObj) {
        try {
            FileOutputStream fout = new FileOutputStream(counter
                    + "SaveGame.ser", true);
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(myClassObj);
            counter++;
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ArrayList<myClass> loadTheData(int saveNum) {
        try {
            FileInputStream fin = new FileInputStream(saveNum + "SaveGame.ser");
            ObjectInputStream ois = new ObjectInputStream(fin);
            ArrayList<myClass> myClassObj = (ArrayList<myClass>) ois.readObject();
            ois.close();
            return myClassObj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

And myClass would look something like this:

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class myClass implements Serializable {
    private static final long serialVersionUID = /* some UID */;
    /* ...
     * class properties
     */

    myClass(/* args */) {
        // Initialize
    }

    /* ...
     * class methods
     */

    private void writeObject(ObjectOutputStream o) throws IOException {
        // Write out to the stream
    }

    private void readObject(ObjectInputStream o) throws IOException,
            ClassNotFoundException {
        // Read in and validate from the stream
    }
}
NanoWizard
  • 1,859
  • 1
  • 16
  • 30
  • am i correct in thinking that this code above doesnt save it in binary format though? – GreenAddiction Jan 03 '16 at 00:18
  • why do i need this private static final long serialVersionUID = /* some UID */; – GreenAddiction Jan 03 '16 at 01:00
  • Serialization [by definition](http://stackoverflow.com/questions/633402/what-is-serialization) *is* "the process of turning an object in memory into a stream of bytes". In java, objects will be serialized according to the standard [Java Object Serialization Specification](http://docs.oracle.com/javase/6/docs/platform/serialization/spec/serialTOC.html). If you want things represented in a different binary format, you'll have to [do it yourself](http://stackoverflow.com/questions/5837698/converting-any-object-to-a-byte-array-in-java). – NanoWizard Jan 03 '16 at 01:56
  • In answer to your second question: [**this**](http://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it). – NanoWizard Jan 03 '16 at 01:58
0

Well .. myClassObj.toString()

Generates a String and thats what you are writing to the output stream. You can expect a string and some other data defining it's size in that case and not a binary representation.

You could just use :

oos.writeObject(myClassObj );

That's because ArrayList implements the Serializable interface. However you will depend on that implementation for what is actually written in that case. The only contract the Serializable interface must support is that the object can be recreated as it was with just the data written to the file.

If you want to write data to the file in raw binary format ( perhaps to read it later from c code for example ) you must write something yourself which cycles the ArrayList. That code would depend on the implementation of myClass so it's hard to give a working examples.

Something like :

for (myClass temp : myClassObj) 
{
        temp.writeBinaryDataToStream(oos);
}

Where writeBinaryDataToStream(oos) is up to you to implement.