I’d like to transfer a file plus some additional data over a tcp socket. It would be really nice if I could do that in one go without having to split the data into several transmissions.
Something like
String data = "some data to be transferred";
File f = new File("myfile");
byte[] fileData = ... //read bytes from file
out.write(data + fileData); //out is some OutputStream
Now, which kind of outputstream would I best use for that? How am I able to separate the data and the file content at the receiving end?
EDIT: I already have a tcp client and server, both using PrintWriter and BufferedInputReader. The only data transmitted so far are simple strings. I’m looking for an easy way to integrate the file transfer.
Since it’s TCP you know that the data is always transferred and that it arrives in the same order it was sent. Knowing that and in which order you sent the data you can just “unpack” the sent data in the same order you sent it.
Another solution would be to wrap the content in an object which implements serializable. If using this technique you don’t have to worry about packing and unpacking since the serialization handles that for you. Here’s an example using this.