- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert an object to byte array in java?
To convert an object to byte array
- Make the required object serializable by implementing the Serializable interface.
- Create a ByteArrayOutputStream object.
- Create an ObjectOutputStream object by passing the ByteArrayOutputStream object created in the previous step.
- Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class.
- Flush the contents to the stream using the flush() method.
- Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
Example
import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class Sample implements Serializable { public void display() { System.out.println("This is a sample class"); } } public class ObjectToByteArray { public static void main(String args[]) throws Exception { Sample obj = new Sample(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(obj); oos.flush(); byte [] data = bos.toByteArray(); } }
- Related Articles
- How to convert byte array to an object stream in C#?
- How to convert an input stream to byte array in java?
- Convert byte primitive type to Byte object in Java
- How to convert BLOB to Byte Array in java?
- How to convert Byte Array to Image in java?
- How to convert Image to Byte Array in java?
- How to convert InputStream to byte array in Java?
- How to convert an object array to an integer array in Java?
- How to convert a PDF to byte array in Java?
- How to convert java bitmap to byte array In android?
- How to convert hex string to byte Array in Java?
- How to convert a byte array to hex string in Java?
- Convert byte Array to Hex String in Java
- Convert Hex String to byte Array in Java
- Program to Convert Byte Array to Writer in Java

Advertisements