LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how to transform an object into an array of bytes on Java! (https://www.linuxquestions.org/questions/programming-9/how-to-transform-an-object-into-an-array-of-bytes-on-java-143078/)

poeta_boy 02-06-2004 03:25 PM

how to transform an object into an array of bytes on Java!
 
hello

I have an Object a and I wanna be able to save it's state on a random access file. I've learned that in order to write on a file I ne ed to transform it into a byte array. But how can I do it?

is there something like a.tobyteArray() ???

once that I've saved it, how can I retreive it for future use?


Thanks thanks thanks a lot!

ter_roshak 02-06-2004 03:40 PM

Have you looked into the 'serializeable' interface? It might do what you want, it allows you to save objects and restore them later.

-Josh

german 02-15-2004 12:26 PM

This code does what you want... you should read the sun docs on the ObjectOutputStream object here: http://java.sun.com/j2se/1.4.1/docs/...putStream.html

Code:


import java.util.*;
import java.io.*;
                                                                               
public class ObjOut {
        public static void main(String[] args) throws Exception {
                                                                               
                // create some object
                ArrayList list = new ArrayList();
                list.add("One");
                list.add("Two");
                list.add("Three");
                                                                               
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream out = new ObjectOutputStream(bos);
                out.writeObject(list);
                                                                               
                RandomAccessFile raf = new RandomAccessFile(
                        new File("./list"), "rw"
                );
                raf.write(bos.toByteArray());
                raf.close();
        }
}

Of course the code could be made more efficient by constructing the ObjectOutputStream with a FileOutputStream, instead of buffering the whole object in memory then writing it through the RandomAccessFile, but that's what you asked for.

HTH

B.

poeta_boy 02-15-2004 07:28 PM

thanks a lot! that's exactly what I was looking for. Thanks!


All times are GMT -5. The time now is 12:00 PM.