1 回答
![?](http://img1.sycdn.imooc.com/545845b40001de9902200220-100-100.jpg)
TA贡献1841条经验 获得超3个赞
File 类不代表文件的内容。 它只是文件路径的表示。这种混淆是 File 类被认为已过时(虽然没有被弃用)并已被Path类取代的众多原因之一。
因此,当您这样做时oos.writeObject(imageFile);,您发送的不是文件的内容,而是该文件的路径。显然,在一台计算机上存在文件路径并不能保证同一路径在另一台计算机上有效。
您必须单独发送文件的内容。一种方法是打开一个 FileInputStream,将它包装在一个 BufferedInputStream 中,然后使用该 BufferInputStream 的transferTo方法:
oos.writeObject(imageFile);
try (InputStream stream =
new BufferedInputStream(new FileInputStream(imageFile))) {
stream.transferTo(oos);
}
在客户端,使用文件的长度来确定要读取的字节数:
File imageFile = (File) ois.readObject();
long length = imageFile.length();
Path imagePath = Files.createTempFile(null, imageFile.getName());
try (FileChannel imageChannel = FileChannel.open(imagePath,
StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
imageChannel.transferFrom(Channels.newChannel(ois), 0, length);
}
Image avatar = new Image(imagePath.toUri().toString());
添加回答
举报