Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending file through ObjectOutputStream and then saving it in Java?

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.

like image 557
ZimZim Avatar asked Dec 16 '22 21:12

ZimZim


1 Answers

A File object represents the path to that file, not its actual content. What you should do is read the bytes 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);
like image 94
Jeffrey Avatar answered Jan 06 '23 08:01

Jeffrey