try-catch-finally中return的执行顺序

在网上查询资料:try,catch和finally最终出口在try或catch中,所以return应该放在try和catch模块最后


写了一个下载资料的demo

package com.edb.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.junit.Test;

public class TestDown {
	@Test
	public void test() {
		String urlStr="http://******.gif";
		String path="F://TestDown";
		String[] urlArr = urlStr.split("\\.");
		String postfix = urlArr[urlArr.length-1];
		String filename=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"."+postfix;
		String filePath=path+"/"+filename;
		File file = new File(path);
		if(!file.exists()){
			file.mkdirs();
		}
		
		Boolean flag = downloadFile(urlStr,filePath);
		if(flag){
			System.out.println("下载文件成功");
		}else{
			System.out.println("下载文件失败");
		}
	}
	
	/**
	 * 下载文件
	 * 
	 * @param urlStr
	 *            下载地址
	 * @param filePath
	 *            存储地址
	 */
	public Boolean downloadFile(String urlStr, String filePath) {
		URL url = null;
		HttpURLConnection httpUrlConnection = null;
		InputStream fis = null;
		FileOutputStream fos = null;
		try {
			url = new URL(urlStr);
			httpUrlConnection = (HttpURLConnection) url.openConnection();
			httpUrlConnection.setConnectTimeout(5 * 1000);
			httpUrlConnection.setDoInput(true);
			httpUrlConnection.setDoOutput(true);
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestMethod("GET");
			httpUrlConnection.setRequestProperty("Charsert", "UTF-8");
			httpUrlConnection.connect();
			fis = httpUrlConnection.getInputStream();
			byte[] temp = new byte[1024];
			int b;
			fos = new FileOutputStream(new File(filePath));
			while ((b = fis.read(temp)) != -1) {
				fos.write(temp, 0, b);
				fos.flush();
			}
			return true;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (fis != null)
					fis.close();
				if (fos != null)
					fos.close();
				if (httpUrlConnection != null)
					httpUrlConnection.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值