步骤简介
- 打开链接:URL类初始化给定网页链接,并调用openConnection()返回一个HttpURLConnection类的父类URLConnection实例。
- 获取链接文本内容:URLConnection实例调用getInputStream()获取输入流,并返回输入流(InputStream)对象,初始化给InputStreamReader,将字节流转换为字符流,并指定字符集编码UTF-8。BufferedReader从字符流中逐行读取文本存入String类型。
- 匹配图片链接:Pattern调用compile(String url)将给定的正则表达式编译,把编译后的表现模式并赋予给Pattern类的实例p,用p.matcher()方法来生成一个Matcher实例m,接着使用该Matcher实例对目标字符串进行匹配。m.find()查找下一个子串,m.group()与组匹配的子串内容。
- 查重:Set集合来判断查找到的子串是否重复,如果不重复则添加到集合里。
- 读取输入流:URL类初始化给定查找到的图片链接,并调用openConnection()返回一个HttpURLConnection的实例,用这个实例调用getInputStream()获取输入流,并初始化给缓冲输入流BufferedInputStream。
- 写入输出流:创建ByteArrayOutputStream实例和byte数组实例,用BufferedInputStream读入到byte数组里,并缓存到字节数组输出流。
- 保存图片数据:FileOutputStream(String name)创建向指定名称的文件中写入数据的输出文件流,并初始化到输出流,然后将字节数组中的数据通过OutputStream写入指定位置。
- 关闭流:对以上的输入输出流的关闭close();
代码示例
Set<String> imageUrlSet = new HashSet<String>();
URLConnection urlconn;
try {
for (int i = 1; i <= 35; i++) {
Thread.sleep(4000);
String url = "http://www.iconarchive.com/show/ios7-icons-by-icons8." + i + ".html";
System.err.println("\r\nStart to crawl: " + url);
urlconn = new URL(url).openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(urlconn.getInputStream(), "utf-8"));
String line = null;
String src = "";
while ((line = reader.readLine()) != null) {
src += line;
}
// System.out.println(src);
Pattern p = Pattern
.compile("http://icons.iconarchive.com/icons/icons8/ios7/128/.+?.png");
Matcher m = p.matcher(src);
while (m.find()) {
String imageUrl = m.group();
if(imageUrlSet.contains(imageUrl)){
continue;
}
imageUrlSet.add(imageUrl);
urlconn = new URL(imageUrl).openConnection();
BufferedInputStream inStream = new BufferedInputStream(
urlconn.getInputStream());
ByteArrayOutputStream bOutStream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int size = 0;
while ((size = inStream.read(buf)) > 0) {
bOutStream.write(buf, 0, size);
}
byte[] srcBin = bOutStream.toByteArray();
String fileName = imageUrl.replaceAll("^.+/", "");
System.out.print(fileName+"\t");
OutputStream osr = new BufferedOutputStream(
new FileOutputStream("ios7/" + fileName));
osr.write(srcBin);
inStream.close();
bOutStream.close();
osr.close();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}