标签:ace exception end public 本地 运行时间 time 自动生成 tin
JAVA快速获取网络图片或者URL图片并保存到本地,直接上代码:
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class DownPicTest {
public static void main(String[] args) throws Exception {
// TODO 自动生成的方法存根
long start=System.currentTimeMillis();
String saveFile="C:\\work\\tmp\\1.jpg";
System.out.println("开始");
String url="https://mmbiz.qpic.cn/mmbiz_jpg/yP97tb1FNrpDsemSP26ibXQqTSdOFvH97LBNlqUkmOjMU2stSN4Jd6MADRlovbU2D8HqjCwZaibSrJ8NibC1Ul3dQ/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1";
getImg(url,saveFile);
long end=System.currentTimeMillis();
System.out.println("运行时间:"+(end-start)/1000+"秒");
}
private static void getImg(String u,String saveFile){
URL url;
try {
url = new URL(u);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5*1000);
InputStream in = conn.getInputStream();
byte[] data = readInputStream(in);
File f = new File(saveFile);
FileOutputStream out = new FileOutputStream(f);
out.write(data);
out.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
private static byte[] readInputStream(InputStream ins) throws IOException {
// TODO 自动生成的方法存根
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = ins.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
ins.close();
return out.toByteArray();
}
}
标签:ace exception end public 本地 运行时间 time 自动生成 tin
原文地址:https://www.cnblogs.com/xuezhaochang/p/14849584.html