【发布时间】:2014-05-25 05:01:55
【问题描述】:
我正在创建一个 MVC Web 应用程序,用户在其中下载 100mb+ 的文件。该文件以块的形式存储在 Oracle 数据库中的多个 BLOB 中。
假设您的模型中有一个名为File 的类和一个HttpServlet 类FileController。
在 File 中,我们有一个方法来获取一个流来读取文件。它的编码是这样的......
ArrayList<InputStream> blobStreams = new ArrayList<InputStream>();
try
{
//<set up and execute JDBC query here>
while (results.next())
{
blobStreams.add(results.getBinaryStream("blob"));
}
return new SequenceInputStream(Collections.enumeration(blobStreams));
}
catch (Exception e)
{
//<exception handling>
}
finally
{
try{if (results!=null)results.close(); }catch(Exception e){};
try{if (statement!=null) statement.close();}catch(Exception e){};
try{if (connection!=null) connection.close();}catch(Exception e){};
}
在FileController 的doGet(...) 方法中,我们从fileContents 流中写入如下。
final int BUFFER_SIZE = 2048;
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = fileContents.read(buffer)) > 0)
{
response.getOutputStream().write(buffer, 0, length);
}
我遇到了一个异常,“java.io.IOException: Closed Connection”大概是因为 JDBC 对象在 File 的 finally 块中关闭。
在不提前关闭流的情况下返回流的最佳 MVC 方式是什么?
【问题讨论】:
标签: java servlets model-view-controller jdbc inputstream