在try里初始化的对象如何在finally里销毁?

nccxl 2006-01-24 01:57:48
我在使用ServletInputStream对象的时候是放在try块里初始化的,希望不管是否出现异常都销毁掉,免得造成内存浪费。现在放在finally里用close()销毁时会报错,说该对象未被初始化。

请问该怎么解决呢?
...全文
224 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
jsnjlc 2006-04-05
  • 打赏
  • 举报
回复
再次学到点东西,谢谢各位大大
nccxl 2006-01-24
  • 打赏
  • 举报
回复
解决了,谢谢sheep219和回帖的各位。
sheep219 2006-01-24
  • 打赏
  • 举报
回复
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.
nccxl 2006-01-24
  • 打赏
  • 举报
回复
我是一个取客户端发过来信息的方法,在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
SW13968086129 2006-01-24
  • 打赏
  • 举报
回复
释放的时候先判断是否实例化成对象了。
try
{
ServletInputStream obj =new ....();
}
finally
{
if (obj!=null)
obj.close();
}
leon528 2006-01-24
  • 打赏
  • 举报
回复
把代码和报错都贴出来啊
songsong2008 2006-01-24
  • 打赏
  • 举报
回复
报什么错你说清楚点啊
songsong2008 2006-01-24
  • 打赏
  • 举报
回复
楼上正解
nccxl 2006-01-24
  • 打赏
  • 举报
回复
回楼上的,这样的话还是会报一个错误。
shuixian0626 2006-01-24
  • 打赏
  • 举报
回复
可以在 try块外声明ServletInputStream in = null;然后在try里进行 in = new ....这样就可以解决了!
M3tdw2A7tVe8Xxhd 2006-01-24
  • 打赏
  • 举报
回复
因该是找不到对象吧,他在try语句块里,是个局部变量,因该在finally里面找不到吧,你试着尝试在try外面初始化

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧