这个代码没什么太大用途,权当复习一下java,里面的例外也处理。作用就是能下载http://www.style.com/fashionshows/complete/slideshow/F2014MEN-AMCQUEEN/这个相册里的30张图。
package fatch;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*
* @author 42
*/
public class Fatch {
/**
* 本程序获取http://www.style.com/fashionshows/complete/slideshow/F2014MEN-AMCQUEEN/相册中的30张图片
* 通过查看图片属性发现其文件名有简单规律,虽不连续但是是有顺序的
* first,last是网址的前半部分和后半部分
* 先判断文件是否存在,然后将文件下载到本地
*/
public static void main(String[] args) throws MalformedURLException, IOException {
String imagesource="";
String first="http://www.style.com/fashion-shows/fall-2014-menswear/london/alexander-mcqueen/collection/_ARC0";
String last=".1366x2048.JPG";
InputStream inputStream;
byte[] getData = null;
for(int i=1,x=0;x<30&&i<=500;i++){
if(i<10){
imagesource=first+"00"+i+last;
}else if((i>=10)&&(i<100)){
imagesource=first+"0"+i+last;
}else if((i>=100)&&(i<1000)){
imagesource=first+i+last;
}
URL url = new URL(imagesource);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
try {
inputStream = conn.getInputStream(); //通过输入流获得图片数据
getData = readInputStream(inputStream); //获得图片的二进制数据
} catch (IOException ex) {
getData=null;
}
if(getData!=null){
File imageFile = new File(i+".JPG");
FileOutputStream fos = new FileOutputStream(imageFile);
fos.write(getData);
fos.close();
System.out.println(x+"picture(s) downloaded");
x++;
}
}
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}