Writing an ObjectOutputStream to a String

  • Thread starter Andreas N Rasmussen
  • Start date
A

Andreas N Rasmussen

Howdy,

I'm using an objectOutputStream to write an object to a file, and the
corresponding objectinputstream to read it later, and this works
great.

Now i'm trying to make it work over a network, by using sockets
(thought maybe RMI was a bit "big" for such a simple project). However
- i'm having some trouble with converting my (serializable) object to
a String or such, so i could send it across the network this way.

What is the standard way of doing this?

anr
 
A

Anders =?iso-8859-1?Q?Engstr=F6m?=

* Andreas N Rasmussen said:
Howdy,

I'm using an objectOutputStream to write an object to a file, and the
corresponding objectinputstream to read it later, and this works
great.

Now i'm trying to make it work over a network, by using sockets
(thought maybe RMI was a bit "big" for such a simple project). However
- i'm having some trouble with converting my (serializable) object to
a String or such, so i could send it across the network this way.

What is the standard way of doing this?

Why sending it as a string? You're already serializing the object to a
file on disk (using ObjectOutputStream).. writing the object to a
socket connection is not different:

Socket targetSocket = ...;
ObjectOutputStream out = new
ObjectOutputStream(targetSocket.getOutputStream());
out.writeObject(mySerializableObject);
out.flush();
out.close();

That's it. On the other side - wrap socket.getInputStream() with an
ObjectInputStream() and read your object like:

MySerializableObject obj =
(MySerializableObject)objInputStream.readObject();

//Anders


--
/**
* Anders Engström, (e-mail address removed)
* -------------------------------------
* Your mind is like an umbrella.
* It doesn't work unless you open it.
* /Frank Zappa
*/
 
J

Jon A. Cruz

Andreas said:
Now i'm trying to make it work over a network, by using sockets
(thought maybe RMI was a bit "big" for such a simple project). However
- i'm having some trouble with converting my (serializable) object to
a String or such, so i could send it across the network this way.

That's bad.

Unlike C/C++, a Java String is not just a simple array of bytes. It's a
fixed sequence of 16-bit Unicode characters. You should never use them
for other things, such as sending binary content or network IO.

In Java, bytes and chars are two different things and represent two
different concepts. Keep them separated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top