RMI客户端/服务器 - 文件传输

13 浏览
0 Comments

RMI客户端/服务器 - 文件传输

我想实现一个Java程序,客户端能够从客户端上传文件(图片、文本等),并将其发送到服务器端,在服务器计算机上将文件存储在一个文件夹中。\n这种做法可行且现实吗?使用EJB是否更好?是否有可用的好资源?

0
0 Comments

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对象的传输即可。以下是可以添加到答案中的相关内容。

0