我在使用ServletInputStream对象的时候是放在try块里初始化的,希望不管是否出现异常都销毁掉,免得造成内存浪费。现在放在finally里用close()销毁时会报错,说该对象未被初始化。请问该怎么解决呢?

解决方案 »

  1.   

    因该是找不到对象吧,他在try语句块里,是个局部变量,因该在finally里面找不到吧,你试着尝试在try外面初始化
      

  2.   

    可以在 try块外声明ServletInputStream in = null;然后在try里进行 in = new ....这样就可以解决了!
      

  3.   

    释放的时候先判断是否实例化成对象了。
    try
    {
      ServletInputStream obj =new ....();
    }
    finally
    {
    if (obj!=null)
        obj.close();
     }
      

  4.   

    我是一个取客户端发过来信息的方法,在JSP页面里面
    -----------代码-----------
    private byte[] ReadPackage(HttpServletRequest request)
    {
      ServletInputStream sis=null;
      byte mStream[]=null;
      int totalRead = 0;
      int readBytes = 0;
      int totalBytes = 0;  try
      {
        totalBytes = request.getContentLength();
        sis = request.getInputStream();
        mStream = new byte[totalBytes];
        while(totalRead < totalBytes)
        {
          readBytes = sis.read(mStream, totalRead, totalBytes - totalRead); // request.getInputStream().read(mStream, totalRead, totalBytes - totalRead);
          totalRead += readBytes;
        }    
      }
      catch (Exception e)
      {
        System.out.println(e.toString());
      }
      finally{
        sis.close();
      }
      return (mStream);
    }-----------报错信息-----------
    "OfficeServer.jsp": Error #: 360 : unreported exception: java.io.IOException; must be caught or declared to be thrown at line 101
      

  5.   

    catch (Exception e)
      {
        System.out.println(e.toString());
      }
      finally{
        sis.close();
      }
      return (mStream);
    }
    当你关闭 sis.close();时候也会抛出一个异常所以你要在这里加上try{}catch(){}看api 里的定义:
    close
    public void close()
               throws IOException
    Closes this input stream and releases any system resources associated with the stream. 
    The close method of InputStream does nothing. 
    Throws: 
    IOException - if an I/O error occurs.
      

  6.   

    解决了,谢谢sheep219和回帖的各位。