- 首页 > it技术 > >
java批量下载图片(通用版)
- 目前存在问题,单线程下载慢,因为readLine是一次读一行,我不知道该怎么加多线程,有想法可以告知下,不胜感激。
- 可以不用看代码,直接按照实际情况修改20,26,32,34行代码即可。
- 附上本文用到的txt文件,只给格式参考,真实url做了隐藏。
BC2001330http://example.com/ybraas3lm6yrtb2u2n.jpg
BC2001331http://example.com/cgcouxu9cp3viyelya.jpg
BC2001332http://example.com/8rbvbd2ipwmjyzdkbh.jpg
/**
* @Author DemoRookie
* @Version 1.0
*/import java.io.*;
import java.net.*;
public class DownLoadImage {
public static void main(String args[]) {
new Thread(new downImage()).start();
} public static class downImage implements Runnable {@Override
public void run() {
long startTime = System.currentTimeMillis();
try {
FileReader file = new FileReader("D:\\DownloadImageSet\\image.txt");
//获取文件流位置
BufferedReader br = new BufferedReader(file);
//构造一个BufferedReader类来读取文件
String imgUrl, picName, document;
// 使用readLine方法,一次读一行
while ((document = br.readLine()) != null) {
//读取当前行截取字符作为图片名(前九个字符,根据实际情况自定制)
picName = document.substring(0, 9) + ".jpg";
/*
* 这里中间多个“s”是因为图片链接开启了强制https,
* 如果没有这种情况就imgUrl = document.substring(9)即可,
* 代表第九位字符之后的全部字符,根据实际情况自定制
*/
imgUrl = document.substring(9, 13) + "s" + document.substring(13);
// System.out.println(imgUrl);
downImages("D:\\downloadImage\\", imgUrl, picName);
//输出文件流位置“D:\\downloadImage\\”
// System.out.println(Thread.currentThread().getName() + "正在下载图片:" + picName);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间:" + (endTime - startTime) + "ms");
}
} private static void downImages(String filePath, String imgUrl, String picName) {
File Dir = new File(filePath);
//若存取文件夹没有,则先创建
if (!Dir.exists()) {
Dir.mkdirs();
}
try {
String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1);
//截取图片文件名
/*
* 文件名里面可能有中文或者空格,所以这里要进行处理,
* 但空格又会被URLEncoder转义为加号,
* 因此要将加号转化为UTF-8格式的%20
* */
String urlTail = URLEncoder.encode(fileName, "UTF-8");
imgUrl = imgUrl.substring(0, imgUrl.lastIndexOf('/') + 1)
+ urlTail.replaceAll("\\+", "\\%20");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}File file = new File(filePath + picName);
//写出路径
InputStream inStream;
try {
URL url = new URL(imgUrl);
// 构造URL
URLConnection con = url.openConnection();
// 打开连接
inStream = con.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//中转站,现将图片数据放到outStream中
byte[] buf = new byte[1024];
int len;
while ((len = inStream.read(buf)) != -1) {
outStream.write(buf, 0, len);
}
inStream.close();
outStream.close();
FileOutputStream op = new FileOutputStream(file);
//图片下载的位置
op.write(outStream.toByteArray());
op.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
推荐阅读