package com.shanghaichengdi.ghjgitem.util;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author gengaoliu
 */
public class ImageDownload {

  public static boolean download(String urlString, String filename) throws Exception {
    boolean flag = false;
    OutputStream os = null;
    InputStream is = null;
    try {
      System.out.println(filename);
      // 构造URL
      URL url = new URL(urlString);
      // 打开链接
      URLConnection con = url.openConnection();
      // 设置请求超时为5s
      con.setConnectTimeout(5 * 1000);
      // 输入流
      is = con.getInputStream();
      // 1K的数据缓冲
      byte[] bs = new byte[1024];
      // 读取到的数据长度
      int len;
      int i = filename.length();
      for (i--; i >= 0 && filename.charAt(i) != '\\' && filename.charAt(i) != '/'; i--)
        ;
      String s_dir = filename.substring(0, i);
      // 输出的文件流
      File dir = new File(s_dir);
      if (!dir.exists()) {
        dir.mkdirs();
      }
      os = Files.newOutputStream(Paths.get(filename));
      // 开始读取
      while ((len = is.read(bs)) != -1) {
        os.write(bs, 0, len);
      }
      flag = true;
      // 完毕，关闭所有链接
      os.close();
      is.close();
    } catch (Exception e) {
      if (os != null) {
        os.close();
      }
      if (is != null) {
        is.close();
      }
    }
    return flag;
  }

  public static void main(String[] args) throws Exception {
    download(
        "http://gi4.md.alicdn.com/bao/uploaded/i4/TB1aRpnHpXXXXaNXVXXXXXXXXXX_!!0-item_pic.jpg",
        "d:\\qfour\\sample.jpg");
  }
}
