使用try catch finally关闭文件流:
写入文件:
import java.io.*; public class exp{ public static void main(String[] args) { //流要在try外面声明,不然finally里面找不到这个流 OutputStream file = null; try{ file = new FileOutputStream("iooooo.txt"); String str = "北邮\n"; byte[] b = str.getBytes(); for (int i=0; i<b.length; i++){ file.write(b[i]); } //在这里,如果发生异常,则close()不能被执行,所以要在finally里close() //file.close(); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(file!=null) file.close(); }catch(Exception e){ e.printStackTrace(); } } } }
读文件:
import java.io.*; public class exp{ public static void main(String[] args) { //流要在try外面声明,不然finally里面找不到这个流 InputStream file = null; try{ file = new FileInputStream("ioo.txt"); int b = 0; while(true){ b = file.read(); if(b == -1){ break; } System.out.println(b); } //在这里,如果发生异常,则close()不能被执行,所以要在finally里close() //file.close(); }catch(Exception e){ System.out.println("try"); }finally{ try{ if(file!=null) file.close(); System.out.println(file); }catch(Exception e){ System.out.println("finally"); } } } }