通常,每当或在另一方中止连接时被调用时,IOException
都会抛出an 。flush()
close()
response.getOutputStream()
通常,关闭数据库连接(和其他资源)应该发生在打开它的finally
块的try
块中,以便在出现异常时无论如何都会关闭它。
总结一下,这个例子应该做到:
String search = getItSomehow();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement(SQL_FIND);
statement.setString(1, search);
resultSet = statement.executeQuery();
if (resultSet.next()) {
response.setContentType(resultSet.getString("contentType"));
response.setContentLength(resultSet.getInt("contentLength")); // Optional.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(resultSet.getBinaryStream("content"));
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
for (int length; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
output.flush();
}
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
} catch (SQLException e) {
throw new ServletException("Something failed at SQL/DB level.", e);
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}