import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
public class Test {
public static void main(String[] args) {
System.out.println(downloadFile("http://photo.jiajiajia.club/lin.jpg"));
}
public static String downloadFile(String remoteUrl) {
try {
URL url = new URL(remoteUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//文件保存位置.保存在系统临时目录
String folder = "D:/test/test/";
File dir = new File(folder);
if (!dir.exists()) {
dir.mkdirs();
}
String fileName = getFileName(url.getPath());
File localFile = new File(dir, fileName);
try (
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(localFile));
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream())
) {
int len = 1024;
byte[] b = new byte[len];
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bos.flush();
bis.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return localFile.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String getFileName(String remoteUrl) {
String decode = null;
try {
decode = URLDecoder.decode(remoteUrl, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
File file = new File(decode);
return file.getName();
}
}