笔记I/O-关闭流

所有的流,无论是输入流还是输出流,使用完毕后都应该关闭。如果不关闭,会占用资源,当量比较大的时候,影响到业务的正常开展。

(1)在try中关闭

try{

File f=new File("d:/e.txt");

FileInputStream fis=new  FileInputStream(f);

byte[]all=new byte[(int)f.length()];

fis.read(all);

for(byte b: all){

System.out.println(b);

}

//在try里关闭流

fis.close();

}catch(IOException e){

e.printStackTrace();

}

(2)在finally中关闭

这是标准的关闭流的方式

1.首先把流的引用声明在try的外面,如果声明在try里面,其作用域无法抵达finally;

2.在finally关闭之前,需要判断该引用是否为空;

3.关闭的时候,需要再一次进行try catch处理

File  f= new File("d:/e.txt");

FileInputStream fis=null;

try{

fis=new FileInputStream(f);

byte[] all=new byte[(int)f.length()];

fis.read(all);

for(byte b: all){

System.out.println(b);

}catch(IOExcption e){

e.printStackTrace();

}finally{

//在finally里关闭流

if(null!=fis)

try{

fis.close();

}catch(IOException e){

e.printStackTrace();

}

}

(3)使用try()方式

把流定义在try()里,try,catch或者finally结束的时候,会自动关闭

File f=new File("d:/e.txt");

//把流定义在try()里

try(FileInputStream fis=new FileInputStream(f)){

byte[] all=new byte[(int) f.length()];

fis.read(all);

for(byte b: all){

System.out.println(b);

}

}catch(IOException e){

e.printStackTrace();

}


猜你喜欢

转载自blog.csdn.net/woyaonaiguaime/article/details/80883611
今日推荐