通过ObjectOutputStream发送文件,然后将其保存在Java中? [英] Sending file through ObjectOutputStream and then saving it in Java?

查看:117
本文介绍了通过ObjectOutputStream发送文件,然后将其保存在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的服务器/客户端应用程序。我正在尝试让服务器通过OutputStream(FileOutputStream,OutputStream,ObjectOutputStream等)发送文件,并在将其保存到实际文件之前在客户端接收它。问题是,我试过这样做,但它一直都失败了。每当我创建文件并将从服务器收到的对象写入其中时,我都会得到一个损坏的图像(我只是将其保存为jpg,但这无关紧要)。以下是最有可能出现故障的代码部分(您在此处看到的所有看似未声明的对象都已预先声明):

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

服务器:

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

客户:

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.

推荐答案

文件对象代表路径到该文件,而不是其实际内容。你应该做的是从该文件中读取字节并通过 ObjectOutputStream 发送它们。

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

这篇关于通过ObjectOutputStream发送文件,然后将其保存在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆