现在的位置: 首页 > web前端 > 正文

inputstreamreader实例样本

2020年07月20日 web前端 ⁄ 共 1516字 ⁄ 字号 评论关闭

  inputstreamreader程序创建或分配资源后,未进行合理释放,将会产生不恰当的资源释放缺陷。在繁忙的程序环境下,可能导致Java虚拟机不能有效的使用I/O对象。


  inputstreamreader缺陷样本


  在下面Java方法中,创建I/O流对象后未进行合理释放,程序依靠Java虚拟机的垃圾回收机制释放I/O流资源,事实上,程序不能确定何时调用虚拟机的finalize()方法。在繁忙的程序环境下,可能导致Java虚拟机不能有效的使用I/O对象。


  publicvoidprocessFile(StringfilePath){try{FileInputStreamfis=newFileInputStream(filePath);InputStreamReaderisr=newInputStreamReader(fis);BufferedReaderbr=newBufferedReader(isr);Stringline="";while((line=br.readLine())!=null){processLine(line);}}catch(FileNotFoundExceptione){log(e);}catch(IOExceptione){log(e);}}


  publicvoidprocessFile(StringfilePath){


  try{


  FileInputStreamfis=newFileInputStream(filePath);


  InputStreamReaderisr=newInputStreamReader(fis);


  BufferedReaderbr=newBufferedReader(isr);


  Stringline="";


  while((line=br.readLine())!=null){


  processLine(line);


  }


  }catch(FileNotFoundExceptione){


  log(e);


  }catch(IOExceptione){


  log(e);


  }


  }


  inputstreamreader示例修复建议:


  应在finally块中释放I/O对象。


  publicvoidprocessFile(StringfilePath){FileInputStreamfis=null;InputStreamReaderisr=null;BufferedReaderbr=null;try{fis=newFileInputStream(filePath);isr=newInputStreamReader(fis);br=newBufferedReader(isr);Stringline="";while((line=br.readLine())!=null){//processLine(line);}}catch(FileNotFoundExceptione){//log(e);}catch(IOExceptione){//log(e);}finally{if(br!=null){try{br.close();}catch(IOExceptione){//log(e);}}if(isr!=null){try{isr.close();}catch(IOExceptione){//log(e);}}if(fis!=null){try{fis.close();}catch(IOExceptione){//log(e);}}}}


  总之,inputstreamreader给大家简单的介绍了一些,希望大家多看看。

抱歉!评论已关闭.