我有这个简单的服务器/客户端应用程序。我试图让服务器通过 OutputStream(FileOutputStream、OutputStream、ObjectOutputStream 等)发送文件,并在将其保存到实际文件之前在客户端接收它。问题是,我已经尝试这样做,但总是失败。每当我创建文件并将从服务器收到的对象写入其中时,我都会得到一个损坏的图像(我只是将其保存为 jpg,但这应该不重要)。以下是代码中最有可能出现故障的部分(您在此处看到的所有看似未声明的对象都已预先声明):
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());
所以,我的问题是我无法在不损坏文件的情况下正确通过流获取对象。
A File
对象代表path该文件,而不是其实际内容。你应该做的是阅读byte
s 从该文件并将其发送到您的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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)