文章目录


背景

之前老大让我在文件服务器下载图片回来给算法做训练,直接从文件服务器下来有点慢,我选择直接访问资源的方式,试了HttpClient,实测下来每张照片需要几百毫秒,太慢了,这五百万数据开多线程也得挺长时间,所以选择了URL来处理,代码如下。

代码

try {
// String path1 = ipPath + snapShot;
URL url = new URL("http://192.168.2.132/group1/M00/35/22/wKgChF1BYuWAZnuiAAFLROcpGQ4962.jpg");
// 打开连接
URLConnection con = url.openConnection();
// 设置请求超时为5s
// con.setConnectTimeout(5 * 1000);
// 输入流
InputStream is = con.getInputStream();

// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
String path = "download";
// 输出的文件流
File sf = new File(path);
if (!sf.exists()) {
sf.mkdirs();
}
String picpath = path + "/" + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
// log.info("#download path:{}", picpath);
OutputStream os = new FileOutputStream(picpath);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}