create object output stream from an object - java

I want to create on ObjectOutputStream, but I don't want to persist the object in a file, so how to do that? All the tutorials(that I found) say only about the file way:
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(new Date());
oos.close();
I want to store the object into a database, so I need to specify a stream in method setBinaryStream() from class PreparedStatement.
Thanks for answering...

Store it in a byte array instead. You can use ByteArrayOutputStream for this. This way you can use PreparedStatement#setBytes().
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(new Date());
oos.close();
// ...
preparedStatement.setBytes(i, baos.toByteArray());
That said, this is pretty a good smell. Are you sure that you need to serialize Java objects into a database? This way they are unindexable and unsearchable. If you for example store each Person serialized in the DB, you cannot do SELECT * FROM person WHERE name = 'John' anymore. The normal practice is to do a 1:1 mapping of the entity and the DB table. The Date for example can perfectly be stored in a DATETIME/TIMESTAMP column.

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(new Date());
os.close();
byte[] data = bos.toByteArray();
So now you have a byte array and do what you want with it.

you specifically need to use an outputstream to write to a database? I would seriously consider looking at the persistence api before attempting to write an outputstream implementation.. since connection details etc, might get tricky to manage.
have a look at link text and remember it can be used in J2SE as well.

Related

How to send size of serialized data before the data itself?

I'm crating a client-server chat application. After discovering the C/C++ approach with sending bytes of data is a real pain in Java (signed bytes are simply hilarious), I started trying to use more convenient methods - specifically Serializable interface and ObjectOutputStream along with ByteArrayOutputStream.
This answer quite describes what I know at the moment.
So, I can convert my object into a byte array, which can then be put into output buffer that is eventually sent (the sending is done asynchronously).
Now with object, I need to send the size of the byte array first - so that the receiving function knows how much data should be read before parsing the object.
So in this code:
out = new ObjectOutputStream(bos);
out.writeObject(this);
return bos.toByteArray();
Can I somehow prepend the object size?
out = new ObjectOutputStream(bos);
out.writeObject(this);
//PSEUDO FUNCTION - beware
out.writeIntOnOffset(out.size(), 0) //Push the size on the beginning of the array
return bos.toByteArray();
Once you have object size just send it:
MyClass obj = ....;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj); // this is what you already have.
int size = baos.length; // now we have size
OutputStream socketStream = .... // I guess you know how to get it.
ObjectOutputStream socketOos = new ObjectOutputStream(socketStream);
socketOos.writeInt(size);
socketOos.write(baos.toByteArray());
You should definitely not mess with the array it self.
Instead you should create a separate method that returns size

How to copy new object java

On my program I want to save some state using stack.
But all object in stack are always the same(the lest i enterd).
here is my Save code:
public void saveState(){
state.setMatrix(temp.clone()); //temp is int[][]
state.setScore(score); //score is int
State newgaGameState = new State(state); //copy consructor
stack.push(newgaGameState);
}
I guess i need to copy the state because the stack save the reference.
How I need to do it??
what I did wrong?
thanks.
You need to use deep copy. So, you can do one of the following:
use state.clone() (of course, you have to check if it creates a deep copy)
serialize and then deserialize object you want to copy
implement this by yourself
You are adding information to state, and then you save gameState. If this is not a typo, it seems you are not really saving anything new.
Use ObjectOutputStream and ObjectInputStream;
WriteObject
FileOutputStream fout = new FileOutputStream(file-full-path);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(your-object);
oos.close();
Read Object
FileInputStream fin = new FileInputStream(file-full-path);
ObjectInputStream ois = new ObjectInputStream(fin);
Your-Class yourObject = (Your-Class) ois.readObject();
ois.close();

Java: Hashmap with contents compiled

I am looking to implement a HashMap with its contents in the bytecode. This would be similar to me serializing the content and then reading it in. But in my experience serialization only works with saving it to a file and then reading it in, I would want this implementation to be faster than that.
But in my experience serialization only works with saving it to a file and then reading it in, I would want this implementation to be faster than that.
Serialization works with streams. Specifically, ObjectOutputStream can wrap any OutputStream. If you want to perform in-memory serialization, you could use ByteArrayOutputStream here.
Similarly on the input side.
You can save your HashMap as byte array using Java Serialization mechanizm
Map map = new HashMap();
map.put(1, 1);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bout);
oos.writeObject(map);
oos.close();
byte[] bytes = bout.toByteArray();
// restore from bytes
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
map = (Map) ois.readObject();
System.out.println(map);
output
{1=1}
not that both keys and values in the Map must be Serializable otherwise it wont work

I want to convert an Object to a byte[] using serialization in Java

Hello I have a class called table. table keeps track of remoteIP, remotePort, macAdd and avgRtt
this is the general structure of it.
public class table implements java.io.Serializable{
String remoteIP;
int remotePort;
String macAdd;
int avgRtt;
public table(String rIP,int rP,String mac,int avRTT){
remoteIP=rIP;
remotePort=rP;
macAdd=mac;
avgRtt=avRTT;
}
}
I'm new to using serialization, I want to be able to convert this into a byte[] and vice-versa.Does anyone know how I would be able to do that?
Something along these lines:
table t;
ByteArrayOutputStream aOS = new ByteArrayOutputStream();
ObjectOutputStream oOS = new ObjectOutputStream(aOS);
oOS.writeObject(t);
oOS.close();
byte[] byteArray = aOS.toByteArray();
The Java docs on serialization are really good, and with the above code and them you should be able to write the code to unserialize it, too! You might also find the JavaDoc for ObjectOutputStream and ByteArrayOutputStream helpful.
You could do this with apache commons quite easily. See here.

How to use ByteArrayOutputStream and DataOutputStream simultaneously in Java?

I'm having quite a problem here, and I think it is because I don't understand very much how I should use the API provided by Java.
I need to write an int and a byte[] into a byte[].
I thought of using a DataOutputStream to solve the data writing with writeInt(int i) and write(byte[] b), and to be able to put that into a byte array, I should use ByteArrayOutputStream method toByteArray().
I understand that this classes use the Wrapper pattern, so I had two options:
DataOutputStream w = new DataOutputStream(new ByteArrayOutputStream());
or
ByteArrayOutputStream w = new ByteArrayOutputStream(new DataOutputStream());
but in both cases, I "loose" a method. in the first case, I can't access the toByteArray() method, and in the second, I can't access the writeInt() method.
How should I use this classes together?
Like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream w = new DataOutputStream(baos);
w.writeInt(100);
w.write(byteArray);
w.flush();
byte[] result = baos.toByteArray();
Actually your second version will not work at all. DataOutputStream requires an actual target stream in which to write the data. You can't do new DataOutputStream(). There isn't actually any constructor like that.
Could you make a variable to hold on to the ByteArrayOutputStream and pass it into the DataOutputStream.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(1);
byte[] result = dos.toByteArray();
Use the former case - wrap DataOutputStream around the ByteArrayOutputStream. Just make sure you save the reference to the ByteArrayOutputStream. When you are finished, close() or at least flush() the DataOutputStream and then use the toByteArray method of the ByteArrayOutputStream.
You could use a stream approach if you connect your outputstream to an inputstream through a PipedInputStream/PipetOutputStream. Then you will consume the data from the inputstream.
Anyway if what you need to do is simple and doesn't not require a stream approach I would use a java.nio.ByteBuffer on which you have
put(byte[] src) for your byte[]
putInt(int value)
and byte[] array() to get the content
You donĀ“t need more like this
Example exampleExample = method(example);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); marshaller.marshal(exampleExample , baos);
Message message = MessageBuilder.withBody(baos.toByteArray()).build();
The Integer class has a method to get the byte value of an int.
Integer.byteValue()

Categories