gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:17:56 24 4
gpt4 key购买 nike

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

服务器:

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

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

最佳答案

File 对象表示该文件的路径,而不是其实际内容。您应该做的是从该文件中读取 byte 并将它们发送到您的 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);

关于java - 通过 ObjectOutputStream 发送文件然后将其保存在 Java 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11593725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com