【问题标题】:How to convert Attachment Object to ByteArray in JAVA如何在 JAVA 中将附件对象转换为 ByteArray
【发布时间】:2016-09-20 18:12:14
【问题描述】:

我正在使用 Apache CXF 在 JAVA 中编写 Web 服务。

所以,我有一个原型如下的方法:

public Response upload(@Multipart("id") int Id, 
            @Multipart("file") Attachment attachment) {

现在,我想将此附件转换为 byte[] 。我该怎么做?

【问题讨论】:

  • 你想将附件的内容读入字节数组,还是序列化?请澄清您的问题,因为它不清楚您在问什么
  • 最后,我必须将它作为 BLOB 存储在数据库中。

标签: java serialization cxf deserialization multipart


【解决方案1】:

以下是读取附件内容并将其存储在字节数组中的方法。或者,您可以直接写信给OutputStream,然后跳过转换为byte[]

        DataHandler dataHandler = attachment.getDataHandler();
        final byte[] data;
        try (InputStream inputStream = dataHandler.getInputStream()) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            final byte[] buffer = new byte[4096];
            for (int read = inputStream.read(buffer); read > 0; read = inputStream.read(buffer)) {
                outputStream.write(buffer, 0, read);
            }
            data = outputStream.toByteArray();
        }

        //todo write data to BLOB

如果您想提高内存效率或附件不适合内存,您可以直接写入 blob 的输出流。只需将ByteArrayOutputStream 替换为OutputStream outputStream = blob.setBinaryStream(1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多