1 import java.io.FileInputStream;
2 import java.io.FileNotFoundException;
3 import java.io.FileOutputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.OutputStream;
7
8 /**
9 * jdk1.9关闭流新特性
10 * 新特性:try(要关闭的流(变量))
11 */
12 public class FileUtils {
13 //该main方法在正式使用后可删除,在此只为测试使用
14 public static void main(String[] args) {
15 try {
16 FileInputStream fis = new FileInputStream("D:\\JAVA重拾\\test1\\test01\\aaa.txt");
17 FileOutputStream fos = new FileOutputStream("D:\\JAVA重拾\\test1\\test01\\bbb.txt");
18 copyFile(fis, fos);
19 } catch (FileNotFoundException e) {
20 e.printStackTrace();
21 }
22 }
23
24 /**
25 * 复制
26 * @param fis
27 * @param fos
28 */
29 public static void copyFile(FileInputStream fis , FileOutputStream fos) {
30 try(fis;fos) { //该新特性为jdk1.9所有(在没有finally的情况下加入需要关闭的流,就不用自己加入关闭方法了)
31 int a ;
32 byte[] flush = new byte[1024];//缓冲容器
33 while((a = fis.read(flush)) != -1) {
34 String str = new String(flush,0,a); //批量解码
35 System.out.println(str);
36 fos.write(flush);
37 fos.flush();
38 }
39 } catch (FileNotFoundException e) {
40 e.printStackTrace();
41 } catch (IOException e) {
42 e.printStackTrace();
43 }
44 }
45 }