Sending file through ObjectOutputStream and then saving it in Java?

霸气de小男生 提交于 2019-12-01 04:56:48

问题


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.


回答1:


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);



回答2:


You are not actually transferring the file, but the File instance from Java. Think of your File object as a (server-)local handle to the file, but not its contents. For transferring the image, you'd actually have to read it on the server first.

However, if you're just going to save the bytes on the client anyway, you can forget about the ObjectOutputStream to begin with. You can just transfer the bytes stored in the File. Take a look at the FileChannel class and its transferTo and transferFrom methods as a start.



来源:https://stackoverflow.com/questions/11593725/sending-file-through-objectoutputstream-and-then-saving-it-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!