4

Is it possible to write objects in Java to a binary file? The objects I want to write would be 2 arrays of String objects. The reason I want to do this is to save persistent data. If there is some easier way to do this let me know.

3
  • I changed my question because I guess I don't want to write classes. Commented Jun 13, 2010 at 0:50
  • 1
    Easier than what? Commented Sep 5, 2016 at 9:34
  • FYI, the Java team in working on re-inventing Java Serialization. See presentation by Viktor Klang, Marshalling: Data-Oriented Serialization, summer 2025. Commented Sep 25 at 19:55

6 Answers 6

13

You could

  1. Serialize the Arrays, or a class that contains the arrays.
  2. Write the arrays as two lines in a formatted way, such as JSON,XML or CSV.

Here is some code for the first one (You could replace the Queue with an array) Serialize

public static void main(String args[]) {
  String[][] theData = new String[2][1];

  theData[0][0] = ("r0 c1");
  theData[1][0] = ("r1 c1");
  System.out.println(theData.toString());

  // serialize the Queue
  System.out.println("serializing theData");
  try {
      FileOutputStream fout = new FileOutputStream("thedata.dat");
      ObjectOutputStream oos = new ObjectOutputStream(fout);
      oos.writeObject(theData);
      oos.close();
      }
   catch (Exception e) { e.printStackTrace(); }
}

Deserialize

public static void main(String args[]) {
   String[][] theData;

   // unserialize the Queue
   System.out.println("unserializing theQueue");
   try {
    FileInputStream fin = new FileInputStream("thedata.dat");
    ObjectInputStream ois = new ObjectInputStream(fin);
    theData = (Queue) ois.readObject();
    ois.close();
    }
   catch (Exception e) { e.printStackTrace(); }

   System.out.println(theData.toString());     
}

The second one is more complicated, but has the benefit of being human as well as readable by other languages.

Read and Write as XML

import java.beans.XMLEncoder;
import java.beans.XMLDecoder;
import java.io.*;

public class XMLSerializer {
    public static void write(String[][] f, String filename) throws Exception{
        XMLEncoder encoder =
           new XMLEncoder(
              new BufferedOutputStream(
                new FileOutputStream(filename)));
        encoder.writeObject(f);
        encoder.close();
    }

    public static String[][] read(String filename) throws Exception {
        XMLDecoder decoder =
            new XMLDecoder(new BufferedInputStream(
                new FileInputStream(filename)));
        String[][] o = (String[][])decoder.readObject();
        decoder.close();
        return o;
    }
}

To and From JSON

Google has a good library to convert to and from JSON at http://code.google.com/p/google-gson/ You could simply write your object to JSOn and then write it to file. To read do the opposite.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 JSON will work here, but be careful with using it for general serialization - it does not support cyclic references.
It's really important to also implement Serializable on every related object you serialize (if any). After you implement, it'll ask you to generate a key. do it as well.
2

You can do it using Java's serialization mechanism, but beware that serialization is not a good solution for long-term persistent storage of objects. The reason for this is that serialized objects are very tightly coupled to your Java code: if you change your program, then the serialized data files become unreadable, because they are not compatible anymore with your Java code. Serialization is good for temporary storage (for example for an on-disk cache) or for transferring objects over a network.

For long-term storage, you should use a standard and well-documented format (for example XML, JSON or something else) that is not tightly coupled to your Java code.

If, for some reason, you absolutely want to use a binary format, then there are several options available, for example Google protocol buffers or Hessian.

1 Comment

The part starting 'if you change your program' is only true if you don't define a serialVersionUID and you violate the rules specified in the Object Serialization Specification, Versioning chapter.
2

One possibility besides serialization is to write Objects to XML files to make them more human-readable. The XStream API is capable of this and uses an approach that is similar to serialization.

http://x-stream.github.io/

Comments

1

If you want to write arrays of String, you may be better off with a text file. The advantage of using a text file is that it can be easily viewed, edited and is usuable by many other tools in your system which mean you don't have to have to write these tools yourself.

You can also find that a simple text format will be faster and more compact than using XML or JSON. Note: Those formats are more useful for complex data structures.

public static void writeArray(PrintStream ps, String... strings) {
    for (String string : strings) {
        assert !string.contains("\n") && string.length()>0;
        ps.println(strings);
    }
    ps.println();
}

public static String[] readArray(BufferedReader br) throws IOException {
    List<String> strings = new ArrayList<String>();
    String string;
    while((string = br.readLine()) != null) {
        if (string.length() == 0)
            break;
        strings.add(string);
    }
    return strings.toArray(new String[strings.size()]);
}

If your start with

String[][] theData = { { "a0 r0", "a0 r1", "a0 r2" } {"r1 c1"} }; 

This could result in

a0 r0
a0 r1
a0 r2

r1 c1

As you can see this is easy to edit/view.

This makes some assumptions about what a string can contain (see the asset). If these assumptions are not valid, there are way of working around this.

Comments

1

You need to write object, not class, right? Because classes are already compiled to binary .class files.

Try ObjectOutputStream, there's an example
http://java.sun.com/javase/6/docs/api/java/io/ObjectOutputStream.html

1 Comment

Beware that serialization is not really good for long-term persistence, see my answer.
0

You can Serialize and Deserialize your custom Object.

How to implement serialization:

  1. add implements Serializable for your class.
  2. implement method private void writeObject(ObjectOutputStream out) throws IOException;
  3. implement private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

You can use a Serializable interface for your implementation:

public class Example implements Serializable {
    private static final long serialVersionUID = 1L;
    private String ExampleDescription exampleDescription;

    // setters and getters

    private void writeObject(ObjectOutputStream oos) 
      throws IOException {
        oos.defaultWriteObject();
        oos.writeObject(exampleDescription.getMainInformation());
    }

    private void readObject(ObjectInputStream ois) 
      throws ClassNotFoundException, IOException {
        ois.defaultReadObject();
        String exampleDescription = (String) ois.readObject();
        this.setExampleDescription(exampleDescription );
    }
}

More details: Baeldung: 3.3. Custom Serialization in Java

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.