RMI客户端/服务器 - 文件传输
RMI客户端/服务器 - 文件传输问题的出现是因为需要在RMI中实现图像的传输,但是没有提供解决方法。下面的代码是一个在通用包中创建TransportableImage类的示例,其中包括了将图像转换为字节数组、通过RMI传输字节数组、重新构建图像以及保存为JPEG文件的方法。
/** * * Randula */ public class TransportableImage { /** * * bufferedImage * * IOException */ public byte[] createByteArray(BufferedImage bufferedImage) throws IOException { byte[] imageBytes = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); JPEGImageEncoder jpg = JPEGCodec.createJPEGEncoder(bos); jpg.encode(bufferedImage); bos.flush(); imageBytes = bos.toByteArray(); bos.close(); return imageBytes; } // 重新构建BufferedImage public BufferedImage createBufferedImage(byte[] imageBytes) throws IOException { InputStream is = new ByteArrayInputStream(imageBytes); JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(is); BufferedImage image = decoder.decodeAsBufferedImage(); is.close(); return image; } // 保存为JPEG图片 public void toFile(File file, byte[] imageBytes) throws IOException { FileOutputStream os = new FileOutputStream(file); os.write(imageBytes, 0, imageBytes.length); os.flush(); os.close(); } }
问题是如何在RMI中实现这些方法,但是还没有给出答案。实际上,RMI支持传输字节数组数据,因此只需将这些方法应用于RMI对象的传输即可。以下是可以添加到答案中的相关内容。