JDK7新特性:
在try的后边可以增加一个( ),在括号中可以定义流对象
那么这个流对象的作用域就在try中有效,try中的代码执行完毕,会自动把流对象释放,不再需要写finally
package com.fgy.demo; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; // JDK7以前写法 public class Demo04CopyFile { public static void main(String[] args) { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream("d:\\a.txt"); outputStream = new FileOutputStream("d:\\b.txt"); int len = 0; /*while ((len = inputStream.read()) != -1) { outputStream.write(len); }*/ byte[] bytes = new byte[1024]; while ((len = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
package com.fgy.demo; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; // JDK7写法 public class Demo05JDK7 { public static void main(String[] args) { try (FileInputStream inputStream = new FileInputStream("d:\\a.txt"); FileOutputStream outputStream = new FileOutputStream("d:\\c.txt")) { int len = 0; byte[] bytes = new byte[1024]; while ((len = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } }catch (IOException e) { e.printStackTrace(); } } }
JDK9新特性:
try前边可以定义流对象
try后边的( )中可以直接引入流对象的名称(变量名)
在try代码执行完毕后会自动释放资源,不用写finally
package com.fgy.demo; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; // JDK9写法 public class Demo05JDK9 { public static void main(String[] args) throws FileNotFoundException { FileInputStream inputStream = new FileInputStream("d:\\a.txt"); FileOutputStream outputStream = new FileOutputStream("d:\\d.txt"); try (inputStream; outputStream) { int len = 0; byte[] bytes = new byte[1024]; while ((len = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } }catch (IOException e) { e.printStackTrace(); } } }