try(){} catch(try-with-resources)

try-with-resources

主要想讲的介玩意儿叫try-with-resources 跟JDK版本有关

1、首先在JDK1.7之前,必须在finally块中手动关闭资源,否则会导致资源的泄露。

/**
 * JDK 1.7之前
 * 完整的进行try-catch形式捕获
 * 必须在finally块中手动关闭资源
 * 
 * @author gary
 */
@Slf4j
public class TryCatchDemo {

	public static String download(String fileUrl) throws IOException {
		
		try {
			FileInputStream inputStream = new FileInputStream(fileUrl);
		} catch (IOException e) {
			log.error("IO异常",e);
		} finally {
		// 先判断是否为空,再关闭资源
			if (inputStream != null)
				inputStream.close();
		}
		return;
	}

2、在JDK1.7,可把待捕获的流单独定义。

/**
 * JDK 1.7
 * 可把流单独的定义出来 再去捕获
 * 
 * @author gary
 */
@Slf4j
public class TryCatchDemo {

	public static String download(String fileUrl) throws IOException {
	
		FileInputStream inputStream = null;
		
		try {
			inputStream = new FileInputStream(fileUrl);
		} catch (IOException e) {
			log.error("IO异常",e);
		} finally {
		// 先判断是否为空,再关闭资源
			if (inputStream != null)
				inputStream.close();
		}
		return;
	}

3、JDK1.8 数据流会在try执行完毕后自动关闭

try-with-resources 是 JDK 7 中一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。所谓的资源(resource)是指在程序完成后,必须关闭的对象。try-with-resources 语句确保了每个资源在语句结束时关闭。所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。

/**
 * JDK 1.8
 * 数据流会在try执行完毕后自动关闭
 * 
 * @author gary
 */
@Slf4j
public class TryCatchDemo {

	public static String download(String fileUrl, HttpServletResponse response){
		// 多个参数以分号隔开
		try(inputStream = new FileInputStream(fileUrl);
		    OutputStream outputStream = response.getOutputStream()) {
		    outputStream.flush();
			log.info("::SUCCESS::");
		} catch (IOException e) {
			log.error("IO异常",e);
		} 
		return;
	}

具体根据IO流返回给前端 可查看另一篇文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值