Send the file through objectoutputstream and save it in Java?

I have this simple server / client application. I'm trying to let the server send files through OutputStream (fileoutputstream, OutputStream, objectoutputstream, etc.) and receive it on the client before saving it to the actual file The problem is, I've tried this, but it's always failing Whenever I create a file and write an object I receive from the server, I get a broken image (I just save it as JPG, but it doesn't matter) The following is the most likely part of the code to fail (all seemingly undeclared objects you see here have been declared in advance):

The server:

ObjectOutputStream outToClient = new ObjectOutputStream(
                        connSocket.getOutputStream());
                File imgFile = new File(dir + children[0]);
                outToClient.writeObject(imgFile);
                outToClient.flush();

customer:

ObjectInputStream inFromServer = new ObjectInputStream(
                clientSocket.getInputStream());
        ObjectOutputStream saveImage = new ObjectOutputStream(
                new FileOutputStream("D:/ServerMapCopy/gday.jpg"));
        saveImage.writeObject(inFromServer.readObject());

So my problem is that I can't get objects correctly through the stream without damaging the file

resolvent

Solution

The file object represents the path to the file, not its actual contents What you should do is read the bytes from the file and send them through 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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>