java.io.IOException : Stream closed 异常

标签 java servlets jdbc ioexception

对于多张图片检索,我调用一个带有 anchor 标记的 PhotoHelperServlet 来获取 imageNames(多张图片),如下所示

PhotoHelperServlet 获取 Images 的名称

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// Getting userid from session

Image image = new Image();
image.setUserid(userid);

ImageDAO imageDAO = new ImageDAO();

try {

    List<Image> imageId = imageDAO.listNames(image);

    if (imageId == null) { 
        // check if imageId is retreived
    }

    request.setAttribute("imageId", imageId);

    //Redirect it to home page
    RequestDispatcher rd = request.getRequestDispatcher("/webplugin/jsp/profile/photos.jsp");
    rd.forward(request, response);

catch (Exception e) {
    e.printStackTrace();
}

在 ImageDAO listNames() 方法中:

public List<Image> listNames(Image image) throws IllegalArgumentException, SQLException, ClassNotFoundException {

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultset = null;
    Database database = new Database();
    List<Image> imageId = new ArrayList<Image>();

    try {

        connection = database.openConnection();
        preparedStatement = connection.prepareStatement(SQL_GET_PHOTOID);                  
        preparedStatement.setLong(1, image.getUserid());
        resultset = preparedStatement.executeQuery();

        while(resultset.next()) {
            image.setPhotoid(resultset.getLong(1));
            imageId.add(image);
        }

    } catch (SQLException e) {
        throw new SQLException(e);
    } finally {
        close(connection, preparedStatement, resultset);
    }
    return imageId;
}

在 JSP 代码中:

<c:forEach items="${imageId}" var="imageid">
    <img src="Photos/${imageid}">
</c:forEach>

在PhotoServlet的doGet()方法中获取一张照片:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String imageid = request.getPathInfo().substring(1);

if(imageid == null) {
    // check for null and response.senderror
}

ImageDAO imageDAO = new ImageDAO();

try {

    Image image = imageDAO.getPhotos(imageid);

    if(image == null) {}

    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {

        input = new BufferedInputStream(image.getPhoto(), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
        if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
    }

} catch(Exception e) {
    e.printStackTrace();
}

在 ImageDAO 的 getPhotos() 方法中

public Image getPhotos(String imageid) throws IllegalArgumentException, SQLException, ClassNotFoundException {

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultset = null;
    Database database = new Database();
    Image image = new Image();

    try {

        connection = database.openConnection();
        preparedStatement = connection.prepareStatement(SQL_GET_PHOTO);                  
        preparedStatement.setString(1, imageid);
        resultset = preparedStatement.executeQuery();

        while(resultset.next()) {
            image.setPhoto(resultset.getBinaryStream(1));
        }

    } catch (SQLException e) {
        throw new SQLException(e);
    } finally {
        close(connection, preparedStatement, resultset);
    }
    return image;
}

在 web.xml 中

<!-- Getting each photo -->
<servlet>
    <servlet-name>Photos Module</servlet-name>
    <servlet-class>app.controllers.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Photos Module</servlet-name>
    <url-pattern>/Photos/*</url-pattern>
</servlet-mapping>

<!-- Getting photo names -->
<servlet>
    <servlet-name>Photo Module</servlet-name>
    <servlet-class>app.controllers.PhotoHelperServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Photo Module</servlet-name>
    <url-pattern>/Photo</url-pattern>
</servlet-mapping>

问题:

我遇到以下异常:

java.io.IOException: Stream closed

在这条线上:

at app.controllers.PhotoServlet.doGet(PhotoServlet.java:94)
while ((length = input.read(buffer)) > 0) {

完整的异常:

java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:134)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at java.io.FilterInputStream.read(FilterInputStream.java:90)
at app.controllers.PhotoServlet.doGet(PhotoServlet.java:94)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

最佳答案

我想基本的代码流程如下所示:

try {
    Get connection, statement, resultset
    Use connection, statement, resultset
    Get inputstream of resultset
} finally {
    Close resultset, statement, connection
}

try {
    Get outputstream
    Use inputstream of resultset, outputstream
} finally {
    Close outputstream, inputstream of resultset
}

ResultSet 的关闭隐式关闭了 InputStream。当 ResultSet 关闭时,您的 JDBC 驱动程序似乎没有将 ResultSetInputStream 完全存储在内存中或临时存储中。也许 JDBC 驱动程序有点简单,或者设计得不好,或者图像太大而无法存储在内存中。谁知道。

我会首先弄清楚您使用的 JDBC 驱动程序实现/版本,然后查阅其开发人员文档以了解可能能够更改/修复此行为的设置。如果你还是想不通,那么你必须重新安排基本的代码流程,如下所示:

try {
    Get connection, statement, resultset
    Use connection, statement, resultset
    try {
        Get inputstream of resultset, outputstream
        Use inputstream of resultset, outputstream
    } finally {
        Close outputstream, inputstream of resultset
    }
} finally {
    Close resultset, statement, connection
}

或者

try {
    Get connection, statement, resultset
    Use connection, statement, resultset
    Get inputstream of resultset
    Copy inputstream of resultset
} finally {
    Close resultset, statement, connection
}

try {
    Get outputstream
    Use copy of inputstream, outputstream
} finally {
    Close outputstream, copy of inputstream
}

第一种方式效率最高,只是代码比较笨拙。第二种方法在复制到 ByteArrayOutputStream 时内存效率低下,或者在复制到 FileOutputStream 时性能低下。如果图像大部分很小并且不超过 1 兆字节或其他内容,那么我只需将其复制到 ByteArrayOutputStream

InputStream input = null;
OutputStream output = null;

try {
    input = new BufferedInputStream(resultSet.getBinaryStream("columnName"), DEFAULT_BUFFER_SIZE);
    output = new ByteArrayOutputStream();
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];

    for (int length; ((length = input.read(buffer)) > 0;) {
        output.write(buffer, 0, length);
    }
} finally {
    if (output != null) try { output.close(); } catch (IOException ignore) {}
    if (input != null) try { input.close(); } catch (IOException ignore) {}
}

Image image = new Image();
image.setPhoto(new ByteArrayInputStream(output.toByteArray()));
// ...

关于java.io.IOException : Stream closed 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6400735/

相关文章:

linux 和文本编辑器中的 java.lang.ClassNotFoundException : com. mysql.jdbc.Driver 异常

java - statements.executeQuery() 之谜。代码没有被执行,也没有捕获异常。

java.net.SocketException : Connection reset with TelnetOutputStream

c# - 模拟列表或模拟对象列表

java jsoup parse如何解析html

java - servlet和jsp有什么区别?

java - 提供 MySQL JDBC 驱动程序密码的最佳实践

java - 无法解析的数据异常

Java:确保 Web 应用程序仅在一个浏览器选项卡中打开

java - 将包添加到 Tomcat 服务器