本文介绍了如何将InputStream转换为DataHandler?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个java Web应用程序,其中文件将存储在数据库中。最初我们通过在结果集上调用 getBytes 来检索数据库中已有的文件:

I'm working on a java web application in which files will be stored in a database. Originally we retrieved files already in the DB by simply calling getBytes on our result set:

byte[] bytes = resultSet.getBytes(1);
...

然后将此字节数组转换为 DataHandler 使用明显的构造函数:

This byte array was then converted into a DataHandler using the obvious constructor:

dataHandler=new DataHandler(bytes,"application/octet-stream");

在我们开始尝试存储和检索更大的文件之前,这很有效。将整个文件内容转储到一个字节数组中,然后构建一个 DataHandler ,只需要太多的内存。

This worked great until we started trying to store and retrieve larger files. Dumping the entire file contents into a byte array and then building a DataHandler out of that simply requires too much memory.

我的直接想法是使用 getBinaryStream 检索数据库中的数据流,并以某种方式将 InputStream 转换为 DataHandler 以节省内存的方式。不幸的是,似乎没有直接的方法将 InputStream 转换为 DataHandler 。我一直在玩的另一个想法是从 InputStream 中读取数据块并将它们写入 OutputStream 的DataHandler 。但是......我找不到一种方法来创建一个空 DataHandler ,它返回一个非null OutputStream 当我打电话给 getOutputStream ...

My immediate idea is to retrieve a stream of the data in the database with getBinaryStream and somehow convert that InputStream into a DataHandler in a memory-efficient way. Unfortunately it doesn't seem like there's a direct way to convert an InputStream into a DataHandler. Another idea I've been playing with is reading chunks of data from the InputStream and writing them to the OutputStream of the DataHandler. But... I can't find a way to create an "empty" DataHandler that returns a non-null OutputStream when I call getOutputStream...

有没有人这样做过?我很感激你能给我的任何帮助或者正确的方向。

Has anyone done this? I'd appreciate any help you can give me or leads in the right direction.

推荐答案

我的方法是写一个自定义实现 DataSource 的类包装你的 InputStream 。然后创建 DataHandler 为其创建 DataSource

My approach would be to write a custom class implementing DataSource that wraps your InputStream. Then create the DataHandler giving it the created DataSource.

这篇关于如何将InputStream转换为DataHandler?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 07:36
查看更多