方式one
public static void main(String[] args) throws Exception { FileWriter fw = null; try { fw = new FileWriter("xhh.txt"); } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
方式two
格式
try (创建流对象语句,如果多个,使用';'隔开) { 代码 } catch(IOException e){ e.printStackTrace(); }
public static void main(String[] args) throws Exception { //该语句确保了每个资源在语句结束时关闭 try (FileWriter fw = new FileWriter("xhh.txt"); FileReader fr = new FileReader("xhh.txt")) { fw.write("xhh.com"); int read = fr.read(); } catch (IOException e) { e.printStackTrace(); } }