服务器端从数据库里读了一张图,得到的是io流,要把这个io流传到客户端。如果直接在finally中关闭io流和Connection,后台就报错,说流关闭,InputStream传不出去。如果只关Connection,InputStream 也会被强制关闭并报错。但不关又没办法释放,连接池很快被占满了,请问怎么解决呢?
public static InputStream ReadImage(String name) {//读取数据库
Connection conn = DataBaseUtil.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
                InputStream in = null;
String sql = "select PositionImage from Distribution where Name=?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, name);
rs = ps.executeQuery();
while (rs.next()) {
in = rs.getBinaryStream("PositionImage");
return in;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
                    try {
//                       in.close();
//                  } catch (Exception e) {
//                e.printStackTrace();
//     }
// DataBaseUtil.close(rs);
// DataBaseUtil.close(ps);
// DataBaseUtil.close(conn);
}
return null;
}//servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name= request.getParameter("name");
InputStream in= TempJDBC.ReadImage(name);
ServletOutputStream out = response.getOutputStream();
int len=0;
byte[] b=new byte[1024];
try {
while((len=in.read(b))!=-1)
{
out.write(b, 0,len);
}

} catch (IOException e) {

e.printStackTrace();
}
out.flush();
out.close();
in.close();
}

解决方案 »

  1.   

    为什么不把图片放在对象载体中直接return,然后取对象中的流不就行了,你这样写肯定是不行的。在流还没有传送出去,你的流就应经关闭了。
      

  2.   


    网络传图片能直接传Bitmap吗,能的话不用io传也行,我之前客户端收图片是这样的
    //客户端获取图片
    public Bitmap getImageResult(String url,int mapSize) {
    Bitmap bm = null;
    try {
    HttpResponse response = getHttpResponse(url);
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK)
    {
    HttpEntity httpEntity = response.getEntity();
    InputStream in = httpEntity.getContent();
    if(in != null){
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = false;
    options.inSampleSize = mapSize;
    bm = BitmapFactory.decodeStream(in, null, options);
    }
    in.close();
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return bm;
    }
      

  3.   

    先读到byte数组,然后,把byte[] 包装成 ByteArrayInputStream,返回ByteArrayInputStream
    或者直接
    改成 byte[] ReadImage(String name)