通过ObjectOutputStream发送文件,然后将其保存在Java中?

Zim*_*Zim 4 java inputstream outputstream file object

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

服务器:

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

客户:

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

所以,我的问题是我无法在没有损坏文件的情况下正确地通过流获取对象.

Jef*_*rey 11

一个File对象表示的路径到该文件,而不是它的实际内容.你应该做的是byte从该文件中读取s并将其发送到您的文件中ObjectOutputStream.

File f = ...
ObjectOutputStream oos = ...

byte[] content = Files.readAllBytes(f.toPath);
oos.writeObject(content);
Run Code Online (Sandbox Code Playgroud)


File f=...
ObjectInputStream ois = ...

byte[] content = (byte[]) ois.readObject();
Files.write(f.toPath(), content);
Run Code Online (Sandbox Code Playgroud)

  • 虽然使用这种方法,您可以在将字节实际写入套接字之前将整个文件读入内存. (3认同)
  • @Jeffrey我明白了这一点,并不意味着要批评您,我的评论仅是对OP的补充说明。 (2认同)