I have this simple Server/Client application. I'm trying to get the Server to send a file through an OutputStream (FileOutputStream, OutputStream, ObjectOutputStream, etc) and receive it at the client side before saving it into an actual file. The problem is, I've tried doing this but it keeps failing. Whenever I create the file and write the object I received from the server into it, I get a broken image (I just save it as a jpg, but that shouldn't matter). Here are the parts of the code which are most likely to be malfunctioning (all the seemingly un-declared objects you see here have already been declared beforehand):
Server:
ObjectOutputStream outToClient = new ObjectOutputStream(
connSocket.getOutputStream());
File imgFile = new File(dir + children[0]);
outToClient.writeObject(imgFile);
outToClient.flush();
Client:
ObjectInputStream inFromServer = new ObjectInputStream(
clientSocket.getInputStream());
ObjectOutputStream saveImage = new ObjectOutputStream(
new FileOutputStream("D:/ServerMapCopy/gday.jpg"));
saveImage.writeObject(inFromServer.readObject());
So, my problem would be that I can't get the object through the stream correctly without getting a broken file.
A File
object represents the path to that file, not its actual content. What you should do is read the byte
s from that file and send those over your ObjectOutputStream
.
File f = ...
ObjectOutputStream oos = ...
byte[] content = Files.readAllBytes(f.toPath);
oos.writeObject(content);
File f=...
ObjectInputStream ois = ...
byte[] content = (byte[]) ois.readObject();
Files.write(f.toPath(), content);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With