Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2006

Tip: Looking for answers? Try searching our database.

Qestion about convert Object to byte[] and convert it back

Thread view: 
davidxiongcn@gmail.com - 04 Nov 2006 14:26 GMT
I need to convert an object to String to store it into structure in our
application, so I write some function to convert Object into byte[] and
convert it back. The following is a test program:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class test {
    private static Object getObjectFromByteArr(byte [] byteArr) throws
java.io.IOException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(new
ByteArrayInputStream(byteArr));
        Object obj = in.readObject();
        in.close();
        return obj;
    }

    private static byte [] getBlobFromObject(Object obj) throws
java.io.IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream objOut = new ObjectOutputStream(out);
        objOut.writeObject(obj);
        byte [] bytes = out.toByteArray();
        objOut.close();
        return bytes;
    }

    public static void main(String [] args) {
        try {
            Integer i  = new Integer(0);
            // it's OK here
            Integer j = (Integer)getObjectFromByteArr(getBlobFromObject(i));
            System.out.println(j);
            // try to convert byte[] to String
            String str = new String(getBlobFromObject(i));
            // and convert it back, exception occurs!!!
            Integer k  = (Integer)getObjectFromByteArr(str.getBytes());
            System.out.println(k);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

But it always report a java.io.InvalidClassException, as it seems the
serialVersionUID has been changed when I convert it to String. I have
compared the convert result and the result of String.getBytes(), they
are different. But I have no idea about how to fix it.
What's wrong with it when I convert a byte[] to String? I tried to use
a characterset in creating new String, the problem remains.
Thomas Hawtin - 04 Nov 2006 14:46 GMT
> I need to convert an object to String to store it into structure in our
> application, so I write some function to convert Object into byte[] and
> convert it back. The following is a test program:

Why do you want to convert it to a String? That's nuts.

>         ByteArrayOutputStream out = new ByteArrayOutputStream();
>         ObjectOutputStream objOut = new ObjectOutputStream(out);
>         objOut.writeObject(obj);
>         byte [] bytes = out.toByteArray();

This converts the *current* received output to a byte[].

>         objOut.close();

This *flushes* unwritten data to the output stream.

>             // try to convert byte[] to String
>             String str = new String(getBlobFromObject(i));
>             // and convert it back, exception occurs!!!
>             Integer k  = (Integer)getObjectFromByteArr(str.getBytes());

> But it always report a java.io.InvalidClassException, as it seems the
> serialVersionUID has been changed when I convert it to String. I have
> compared the convert result and the result of String.getBytes(), they
> are different. But I have no idea about how to fix it.
> What's wrong with it when I convert a byte[] to String? I tried to use
> a characterset in creating new String, the problem remains.

Works for me, but then perhaps you have a different default character
set. I'm using ISO8859-15; perhaps you are using a Microsoft proprietary
character set. Look at the API docs for the methods you have used. (I
think methods implicitly using the default character set or locale
should be deprecated.)

You could use String(byte[],int) and
String.getBytes(int,int,byte[],int), but they are deprecated for good
reason.

Tom hawtin
davidxiongcn@gmail.com - 04 Nov 2006 14:55 GMT
Another question: if I use 8859_1, when there is \0 in byte[], will it
cause problem? Will the bytes after the byte \0 be lost?
davidxiongcn@gmail.com - 04 Nov 2006 14:49 GMT
I think I have solved the problem by using characterset: 8859_1. But
what's the default characterset? Why it can cause the problem above?
Thomas Hawtin - 04 Nov 2006 16:17 GMT
> I think I have solved the problem by using characterset: 8859_1. But
> what's the default characterset? Why it can cause the problem above?

Latin 1 should work, by coincidence.

The default character set is whatever happens to be configured. So not
something you want to rely upon.

Anyway, attempting to store binary data in Strings is a really bad idea.

Tom Hawtin
Wesley Hall - 04 Nov 2006 17:11 GMT
> I need to convert an object to String to store it into structure in our
> application, so I write some function to convert Object into byte[] and
[quoted text clipped - 48 lines]
> What's wrong with it when I convert a byte[] to String? I tried to use
> a characterset in creating new String, the problem remains.

If you really must do this, then you should run the object byte array
through a Base64 encoder first. The result will be a byte[] that can be
safely converted to 7-bit ASCII for storage as text. Email systems use
this basic mechanism for sending attachments. Jakarta commons codec
contains a Base64 encoder/decoder class, you can find it at
http://jakarta.apache.org/commons/codec/


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.