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.
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();
Related
I have a query that is in the below code i have a file name as shown below
String filename = "C:\\abcd\\Ttre.xls";
which later on i am passing to FileInputStream object as shown below
FileInputStream fileStream = new FileInputStream(filename);
workbook = new HSSFWorkbook(fileStream);
the happy case above was that filename was hardcoded which was pass to the FileInputStream object but lets say if some one is giving me file in form of byte array then how to deal with that case for example
as shown below
public void abcd( byte[] excelByteStream) {
//how to pass the the byte array file to the FileInputStream object
}
so in that case how we would pass the bytestream file to the FileInputStream object please advise
You can't. FileInputStream is a type of InputStream that expects a file as input.
To use a byte array, you would use java.io.ByteArrayInputStream, which is also another type of InputStream.
Just make sure that whatever is expecting an input stream is defined to accept the more generic InputStream. (e.g.: public HSSFWorkbook(InputStream inputStream) { // HSSFWorkbook constructor definition)
Documentation: ByteArrayInputStream.
EDIT: A more complete example
If your HSSFWorkbook class has the constructor currently defined as:
public HSSFWorkbook(FileInputStream inputStream) {
// ...
}
... you would want to change it to accept the more generic InputStream class, which would now allow you to pass it either a FileInputStream or a ByteArrayInputStream instance depending on where you call it from. Like this:
public HSSFWorkbook(InputStream inputStream) {
// ...
}
Then you can instantiate your HSSFWorkbook using either option:
FileInputStream fileStream = new FileInputStream(filename);
workbook = new HSSFWorkbook(fileStream); // still works
... or ...
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(excelByteStream);
workbook = new HSSFWorkbook(byteArrayInputStream ); // now also works.
Use ByteArrayInputStream instead of FileInputStream:
workbook = new HSSFWorkbook(excelByteStream);
In xmlrpc objects need to be serialized before they can be transmitted across a network, so this is what I am trying to do.
addAuthorName = txtAddAuthorName.getText();
int addArticleNumber = Integer.parseInt(txtAddArticleNumber.getText());
newArticle = new Article(addAuthorName, addArticleNumber);
ObjectOutputStream oos;
oos = new ObjectOutputStream(
new ByteArrayOutputStream());
oos.writeObject(newArticle);
Vector<Object> addArticleArglist = new Vector<Object>();
addArticleArglist.addElement(oos);
System.out.println(oos);
// make the call
String callit = ("GetSize.addHash");
articleID = (Integer) client.execute(callit, addArticleArglist);
The problem I am getting is that my program will not accept the outputstream that is contained in the vector the error given is
unsupported Java type: class java.io.ObjectOutputStream
You can only serialize objects that implement the java.io.Serializable interface. Below statement adds ObjectOutputStream to the Vector which doesn't implement that interface.
addArticleArglist.addElement(oos);
I doesn't see any reason why you have to add that to Vector.
The serialization happens automatically. You don't need to undertake further action to serialize the object—just use it as a param, and it will automatically be serialized.
I know that in J2ME I can get a byte[] object from a String object by using the getBytes() method. My question is : is it possible to get a byte[] object from any other class type ? In addition : is it possible to get a byte[] object from a user-defined class object ?
Is it possible to get a byte[] object from any other class type ?
Some classes may implement a simular service.
Is it possible to get a byte[] object from a user-defined class object ?
Not without you writing the conversion yourself.
Example how to do it yourself (just note that the DataOutputStream handles the conversion, for example which byte order that is used):
ByteArrayOutputStream out = new ByteArrayOutputStream();
{
// conversion from "yourObject" to byte[]
DataOutputStream dos = new DataOuputStream(out);
dos.writeInt(yourObject.intProperty);
dos.writeByte(yourObject.byteProperty);
dos.writeFloat(yourObject.floatProperty);
dos.writeChars(yourObject.stringProperty);
dos.close();
}
byte[] byteArray = out.toByteArray();
hello i have a basic client-server system running using java sockets.
my problem is, that an object that i send from the client to the server does not contain the correct data after it has been sent once.
the first time i send it, it arrives with the correct values, but when i send it another time with different values, it still arrives at the server with the same values as the first time. it also happens if i send a completely different instance of that class. it always arrives with the data, which have been sent the very first time.
when i try this with other objects like java.lang.String it seems to work.
the problematic class looks like this:
public class Vector3f implements Serializable {
private static final long serialVersionUID = 2838034155614698213L;
public float x, y, z;
}
i use objectinputstream and objectoutputstream on both the server and the client to send and receive objects.
let me know, if you need any more information about the system.
thanks!
My guess is that you're changing the values of the fields and then retransmitting the same object. The ObjectOutputStream will notice that it's already sent the original object, and just send a reference the second time.
You could avoid this by calling reset() on the ObjectOutputStream - but I'd be tempted to just use separate instances anyway, possibly even making the class immutable. (Public mutable fields are almost never a good idea.)
The best way in case of serialization you should convert the object into a byte array object and then write into the socket.
// Serialize to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(object);
out.close();
// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
// Deserialize from a file
File file = new File("filename.ser");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
Object obj = (Object) in.readObject();
in.close();
// Get some byte array data
byte[] bytes = getBytesFromFile(file);
// see Reading a File into a Byte Array for the implementation of this method
// Deserialize from a byte array
in = new ObjectInputStream(new ByteArrayInputStream(bytes));
in.close();
I am about to write junit tests for a XML parsing Java class that outputs directly to an OutputStream. For example xmlWriter.writeString("foo"); would produce something like <aTag>foo</aTag> to be written to the outputstream held inside the XmlWriter instance. The question is how to test this behaviour. One solution would of course be to let the OutputStream be a FileOutputStream and then read the results by opening the written file, but it isn't very elegant.
Use a ByteArrayOutputStream and then get the data out of that using toByteArray(). This won't test how it writes to the stream (one byte at a time or as a big buffer) but usually you shouldn't care about that anyway.
If you can pass a Writer to XmlWriter, I would pass it a StringWriter. You can query the StringWriter's contents using toString() on it.
If you have to pass an OutputStream, you can pass a ByteArrayOutputStream and you can also call toString() on it to get its contents as a String.
Then you can code something like:
public void testSomething()
{
Writer sw = new StringWriter();
XmlWriter xw = new XmlWriter(sw);
...
xw.writeString("foo");
...
assertEquals("...<aTag>foo</aTag>...", sw.toString());
}
It's simple. As #JonSkeet said:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// pass the baos to be writed with "value", for this example
byte[] byteArray = baos.toByteArray();
Assert.assertEquals("value", new String(byteArray));