I am trying to send a file through a java socket and receive it through another. However, this happens:
Send Content:
/*
This is simply a file to transfer
*/
Received:
so basically I cannot escape the received content on stack overflow. It is basically a bunch of unreadable bytes (about 32 bytes worth) and then the message I sent.
OutputStream os = sock.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(mybytearray);
oos.flush();
oos.close();
And for the client:
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
FileOutputStream fos = new FileOutputStream("newfile.java");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
bos.write(mybytearray, 0 , current);
bos.flush();
bos.close();
sock.close();
Why go through
ObjectOutputStream? Either use theOutputStreamdirectly through thewritemethod, or choose for instanceDataOutputStreamif you find it neccessary.Besides, you should not use the
Readerclasses for transferring binary data. From the api ofReader:A complete “send file over socket” example can be found here:
Transfer a file via Socket.
Key server-side code:
Key client-side code: