java JDK17.前后关于IO流的异常处理

JDK1.6前:

private static void handleException() throws IOException {
		FileOutputStream fos =null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("d:\\iotest\\1.txt");
			fos = new FileOutputStream("d:\\iotest\\11.txt");
			
			int b;
			while((b = fis.read()) != -1) {
				fos.write(b);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			/**
			 * 能关一个尽量关一个JDK1.6以前
			 */
			try {
				if(fis != null) {
					fis.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			} finally {
				if(fos != null) {
					fos.close();
				}
			}
			
		}
	}

JDK1.7:

try(//创建流对象) {
     //TODO Something
}

public static void main(String[] args) throws IOException {
		/**
		 * JDK1.7 自行关闭流   
		 * implements  AutoCloseable就能关闭
		 */
		try(
				FileInputStream fis = new FileInputStream("d:\\iotest\\1.txt");
				FileOutputStream fos = new FileOutputStream("d:\\iotest\\2.txt");
				MyClose m = new MyClose();
		){
			int b;
			while((b = fis.read()) != -1) {
				fos.write(b);
			}
		}
	}



猜你喜欢

转载自blog.csdn.net/pastthewind/article/details/80158686