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();
    }

    }
  • 相关阅读:
    POJ 2000 Gold Coins
    HDU 5804 Price List
    POJ 1316 Self Numbers
    HDU 5783 Divide the Sequence
    rabbitmq基础使用
    centos7安装RabbitMQ
    编程之路┊一个程序员走过的路
    jquery layer弹出层插件
    SWFUpload 2.5.0版 官方说明文档 中文翻译版
    C# 格式化字符串,日期,字符串操作汇总
  • 原文地址:https://www.cnblogs.com/linjiqin/p/2064711.html
Copyright © 2011-2022 走看看