-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.

Ritesh
  • 1,053
  • 5
  • 16
  • 29
  • [serialization explained](http://java.sun.com/developer/technicalArticles/Programming/serialization) – UmNyobe Apr 23 '12 at 09: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. – Ritesh Apr 23 '12 at 09:46
  • If you can't use serialization, then this question should be rephrased. And yes, it has been asked before: http://stackoverflow.com/questions/239280/which-is-the-best-alternative-for-java-serialization – mindas Apr 23 '12 at 09: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.* – user207421 Apr 23 '12 at 10:13

1 Answers1

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();
maksimov
  • 5,792
  • 1
  • 30
  • 38
  • 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 Apr 23 '12 at 09:49
  • @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: http://stackoverflow.com/questions/2563340/how-to-convert-a-non-serializable-object-to-byte-array – maksimov Apr 23 '12 at 09:56