|
|
|
1000 Java Tips ebook
|
|
 

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!. |
|
How can I convert any Java Object into byte array? And byte array to file object
|
JavaFAQ Home » General Java

Question: How can I convert any Java Object into byte array?
Answer: Very elegant way I found on SUN's web site:
| Code: |
public static byte[] getBytes(Object obj) throws java.io.IOException{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
byte [] data = bos.toByteArray();
return data;
}
|
How to convert bytes[] into File object?
Please remember that " byte[]" is byte array and it is just a bunch of bytes.
So, when we say that we want to save bytes[] into File object it means that we want to write the contents of your byte array to some file on your hard drive.
It is very easy to save your bytes to File, look at the example below, copy and paste it into your program:
| Code: |
String fileName;
byte [] justByteArray;
String fileName = "saveBytesToFileObject";
FileOutputStream outStream = <strong>new </strong> FileOutputStream(fileName);
outStream.write(justByteArray); out.close();
|
Reference: class File description in SUN's API: File
Printer Friendly Page
Send to a Friend
Search here again if you need more info!
|
|
|