在网上查询资料: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();
}
}
}
}