JDK新特性之一,

try(
只要是实现了AutoCloseable接口就可以在try语句块退出的时候自动调用close方法关闭流资
){
}catch(){
}

1.没用JDK7特性实例:

package day20200817;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo05 {
    
    
	public static void main(String[] args) throws IOException {
    
    

		FileInputStream fis = new FileInputStream("a.txt");
		FileOutputStream fos = new FileOutputStream("b.txt");
		byte[] a = new byte[1024 * 8];
		int i;
		while ((i = fis.read(a)) != -1) {
    
    
			fos.write(a, 0, i);

		}
		fis.close();
		fos.close();
	}

}

用了JDK7的特性

package day20200817;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo06 {
    
    
	public static void main(String[] args) throws IOException {
    
    
		try (	FileInputStream fis = new FileInputStream("a.txt");
				FileOutputStream fos = new FileOutputStream("b.txt");){
    
    
			byte[] a = new byte[1024 * 8];
			int i;
			while ((i = fis.read(a)) != -1) {
    
    
				fos.write(a, 0, i);

			}
			
		} catch (FileNotFoundException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

Supongo que te gusta

Origin blog.csdn.net/qq_43472248/article/details/108062123
Recomendado
Clasificación