tags:

views:

4662

answers:

12

I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me?

LinkedList<Diff_match_patch.Patch> patches = // whatever...
FileOutputStream fileStream = new FileOutputStream("foo.ser");
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(patches1);
os.close();

FileInputStream fileInputStream = new FileInputStream("foo.ser");
ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream);
Object one = oInputStream.readObject();
LinkedList<Diff_match_patch.Patch> patches3 = (LinkedList<Diff_match_patch.Patch>) one;
os.close();
+3  A: 

How about writing the data to a ByteArrayOutputStream instead of a FileOutputStream?

Otherwise, you could serialize the object using XMLEncoder, persist the XML, then deserialize via XMLDecoder.

Outlaw Programmer
A: 

Use a O/R framework such as hibernate

Kristian
+2  A: 

How about persisting the object as a blob

Kristian
A: 

you can use UUEncoding

CiNN
+2  A: 

If you're storing an object as binary data in the database, then you really should use a BLOB datatype. The database is able to store it more efficiently, and you don't have to worry about encodings and the like. JDBC provides methods for creating and retrieving blobs in terms of streams. Use Java 6 if you can, it made some additions to the JDBC API that make dealing with blobs a whole lot easier.

If you absolutely need to store the data as a String, I would recommend XStream for XML-based storage (much easier than XMLEncoder), but alternative object representations might be just as useful (e.g. JSON). Your approach depends on why you actually need to store the object in this way.

Daniel Spiewak
+1  A: 

The serialised stream is just a sequence of bytes (octets). So the question is how to convert a sequence of bytes to a String, and back again. Further it needs to use a limited set of character codes if it is going to be stored in a database.

The obvious solution to the problem is to change the field to a binary LOB. If you want to stick with a characer LOB, then you'll need to encode in some scheme such as base64, hex or uu.

Tom Hawtin - tackline
A: 

Thanks for great and quick replies. I will gives some up votes inmediately to acknowledge your help. I have coded the best solution in my opinion based on your answers.

LinkedList<Patch> patches1 = diff.patch_make(text2, text1);
try {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(bos);
    os.writeObject(patches1);
    String serialized_patches1 = bos.toString();
    os.close();


    ByteArrayInputStream bis = new ByteArrayInputStream(serialized_patches1.getBytes());
    ObjectInputStream oInputStream = new ObjectInputStream(bis);
    LinkedList<Patch> restored_patches1 = (LinkedList<Patch>) oInputStream.readObject();   



        // patches1 equals restored_patches1
    oInputStream.close();
} catch(Exception ex) {
    ex.printStackTrace();
}

Note i did not considered using JSON because is less efficient.

Note: I will considered your advice about not storing serialized object as strings in the database but byte[] instead.

Sergio del Amo
"ByteArrayOutputStream.toString converts using the *platform default encoding*. Are you sure you want that? Particularly as an arbitrary byte array is not valid UTF8. Further, the database is going to mangle it."
Tom Hawtin - tackline
You should take the above comment from Tom Hawtin seriously
anjanb
Not to mention long-term storage of serialized objects is not a great idea and not recommended
Steve g
"Note i did not considered using JSON because is less efficient."How about using google's protocol buffers for efficiency ?Also, Steve g's idea makes perfect sense. One way to store serialized data in a DB yet make it available for languages other than java is again, protocol buffers.
anjanb
+11  A: 

Sergio.

You should use BLOB. It is pretty straighforward with JDBC.

The problem with the second code you posted it's the encoding you should additionally encode the bytes to make sure none of them fails.

If you still want to write it down into a String you can also encode the bytes using Base64.

Java does not have a "public" implementation for that ( though sun.misc, and java.util.prefs have implementations and the source is available, but check the license for those )

Or you can use the following simple Base64Coder open source impl.

http://www.source-code.biz/snippets/java/2.htm

Still you should use CLOB as data type, because you don't know how long the serialized data is going to be.

Here is a sample of how to use it.

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

/** 
 * Usage sample serializing SomeClass instance 
 */
public class ToStringSample {
    public static void main( String [] args )  throws IOException,
                                                      ClassNotFoundException {
        String string = toString( new SomeClass() );
        System.out.println(" Encoded serialized version " );
        System.out.println( string );
        SomeClass some = ( SomeClass ) fromString( string );
        System.out.println( "\n\nRestituted object");
        System.out.println( some );


    }
    /** Read the object from Base64 string. */
    private static Object fromString( String s ) throws IOException ,
                                                        ClassNotFoundException {
        byte [] data = Base64Coder.decode( s );
        ObjectInputStream ois = new ObjectInputStream( 
                                        new ByteArrayInputStream(  data ) );
        Object o  = ois.readObject();
        ois.close();
        return o;
    }
    /** Write the object to a Base64 string. */
    private static String toString( Serializable o ) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream( baos );
        oos.writeObject( o );
        oos.close();
        return new String( Base64Coder.encode( baos.toByteArray() ) );


    }
}

/** Test subject. A verey simple class */ 
class SomeClass implements Serializable{
    int i = Integer.MAX_VALUE;
    String s = "ABCDEFGHIJKLMNOP";
    Double d = new Double( -1.0 );
    public String toString(){
        return  "SomClass instance says: Don't worry, " +
                "I'm healty  look, my data is i = "+ i  + ", s = "+ s + ", d = "+ d;
    }
}

Output:

C:\oreyes\samples\java\encode>javac *.java

C:\oreyes\samples\java\encode>java ToStringSample
Encoded serialized version
rO0ABXNyAAlTb21lQ2xhc3PSHbLk6OgfswIAA0kAAWlMAAFkdAASTG
phdmEvbGFuZy9Eb3VibGU7TAABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3
hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSi
lr+wQCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQ
uU4IsCAAB4cL/wAAAAAAAAdAAQQUJDREVGR0hJSktMTU5PUA==


Restituted object
SomClass instance says: Don't worry, I'm healty  look, 
my data is i = 2147483647, s = ABCDEFGHIJKLMNOP, d = -1.0
OscarRyz
+1 for putting a lot of effort into this answer.
Outlaw Programmer
+1 if you REALLY need strings, then base64+clob is the way to go.
John Gardner
+1, Small improvement. Better to use interface Serializable instead of plain Object in toString() method: private static String toString(Serializable object)
zdmytriv
If we try to store the object as an byte array instead of string, then we can achieve the samething without using BASE64.
Sudar
Very helpful, thanks again after 1 year..
Deniz Acay
A: 

Take a look at the java.sql.PreparedStatement class, specifically the function

http://java.sun.com/javase/6/docs/api/java/sql/PreparedStatement.html#setBinaryStream(int,%20java.io.InputStream)

Then take a look at the java.sql.ResultSet class, specifically the function

http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html#getBinaryStream(int)

Keep in mind that if you are serializing an object into a database, and then you change the object in your code in a new version, the deserialization process can easily fail because your object's signature changed. I once made this mistake with storing a custom Preferences serialized and then making a change to the Preferences definition. Suddenly I couldn't read any of the previously serialized information.

You might be better off writing clunky per property columns in a table and composing and decomposing the object in this manner instead, to avoid this issue with object versions and deserialization. Or writing the properties into a hashmap of some sort, like a java.util.Properties object, and then serializing the properties object which is extremely unlikely to change.

Josh
+1  A: 

You can use the build in classes sun.misc.Base64Decoder and sun.misc.Base64Encoder to convert the binary data of the serialize to a string. You das not need additional classes because it are build in.

A: 
/// Serialize an instance of an object to a string.        
public string Serialize(object instance)        
{            
    StringBuilder sb = new StringBuilder();            
    StringWriter sw = new StringWriter(sb);            
    XmlSerializer serializer = new XmlSerializer(instance.GetType());            
    serializer.Serialize(sw, instance);            
    return sb.ToString();        
}
Blend Master
+1  A: 

XStream provides a simple utility for serializing/deserializing to/from XML, and it's very quick. Storing XML CLOBs rather than binary BLOBS is going to be less fragile, not to mention more readable.

skaffman