-2

I have an array of person class

Class Person
{}

Could anyone please help me to convert Person[] array to inputstream or to a byteStream?

Thanks in advance.

4
  • serialization explained Commented Apr 23, 2012 at 9:08
  • Thanks for reply...Basically I have used Person class as example but I have a class that comes with a jar and it is not serializable. In this case I cannot go ahead with the serialization. Commented Apr 23, 2012 at 9:46
  • If you can't use serialization, then this question should be rephrased. And yes, it has been asked before: stackoverflow.com/questions/239280/… Commented Apr 23, 2012 at 9:53
  • Your question is meaningless. If your class isn't serializable, you can't serialize it, so there is nothing you can 'convert it ... to input stream or byte stream' from. Commented Apr 23, 2012 at 10:13

1 Answer 1

1

To be able to write (serialise) your objects to streams, your class should implement Serializable interface. In most cases you don't need to do anything except for adding the "implements Serializable" clause in your class definition:

class Person implements Serializable {
// your class's fields and methods
}

Then, of course, you are not writing to the input stream, but to an output stream:

Person p = new Person();
// some more code here...
OutputStream os = new FileOutputStream("persons.txt"); // open file as a stream
os.write(person); // write person object to the stream
os.close(); // close the stream

To convert to a byte array you will have to use serialization still:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(person);
byte[] bytes = baos.toByteArray();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Maksimov, but I dont want to write my object to a file rather I want a byte array also I cant add serializable to it since it is packaged in a jar file.
@Ritesh I've updated the answer to cover byte array case, but for cases when the object is not serializable, you'll have to workaround this. See this for example: stackoverflow.com/questions/2563340/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.