zoukankan      html  css  js  c++  java
  • 十五、从互联网获取图片且保存到指定目录

    package com.ljq.test;

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;

    import org.junit.Test;

    /**
    * 从互联网获取图片且保存到指定目录里
    *
    *
    @author jiqinlin
    *
    */
    public class InternetTest {

    @SuppressWarnings(
    "static-access")
    @Test
    public void getImg() throws Exception {
    String urlPath
    = "http://i0.itc.cn/20101116/62d_67fd2b2a_207d_4de2_a4f9_fb93cc8da492_0.jpg";
    URL url
    = new URL(urlPath);
    HttpURLConnection conn
    = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(
    6*1000); // 注意要设置超时,设置时间不要超过10秒,避免被android系统回收
    if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
    InputStream inSream
    = conn.getInputStream();
    //把图片保存到项目的根目录
    new InternetTest().readAsFile(inSream, new File("sohu.jpg"));
    }

    public static void readAsFile(InputStream inSream, File file) throws Exception{
    FileOutputStream outStream
    = new FileOutputStream(file);
    byte[] buffer = new byte[1024];
    int len = -1;
    while( (len = inSream.read(buffer)) != -1 ){
    outStream.write(buffer,
    0, len);
    }
    outStream.close();
    inSream.close();
    }

    }
  • 相关阅读:
    springCloud、springBoot学习
    企业级应用和互联网应用的去区别
    软件工程 期末总结
    四则运算
    读后感
    软件工程自评
    wc
    自我介绍
    学习javaE的目标
    基于Caffe的DeepID2实现(中)
  • 原文地址:https://www.cnblogs.com/linjiqin/p/2064711.html
Copyright © 2011-2022 走看看