android下载网络图片

来源:互联网 发布:网址导航手机版源码 编辑:程序博客网 时间:2024/04/27 11:24
[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. package com.home;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.File;  
  5. import java.io.FileOutputStream;  
  6. import java.io.InputStream;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.URL;  
  9.   
  10. public class DownloadImage {  
  11.     public DownloadImage() {  
  12.         try {  
  13.             getImage();  
  14.         } catch (Exception e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
  18.   
  19.     public static void main(String[] args) {  
  20.         new DownloadImage();  
  21.     }  
  22.   
  23.     /** 
  24.      * 读取网络图片 
  25.      *  
  26.      * @throws Exception 
  27.      */  
  28.     public void getImage() throws Exception {  
  29.         // 图片url路劲  
  30.         String urlpath = "http://pica.nipic.com/2008-05-23/200852381811521_2.jpg";  
  31.         // 建立URL对象,抛出异常  
  32.         URL url = new URL(urlpath);  
  33.         // 得到HttpURLConnection对象  
  34.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  35.         // 声明请求方式  
  36.         conn.setRequestMethod("GET");  
  37.         // 设置连接超时  
  38.         conn.setConnectTimeout(6 * 1000);  
  39.         // 连接成功  
  40.         if (conn.getResponseCode() == 200) {  
  41.             // 得到服务器传回来的数据,相对我们来说输入流  
  42.             InputStream inputStream = conn.getInputStream();  
  43.             // 得到数据  
  44.             byte[] data = readInStream(inputStream);  
  45.             // 创建保存文件  
  46.             File file = new File("C:/image.jpg");  
  47.             // 创建一个文件输出流  
  48.             FileOutputStream outputStream = new FileOutputStream(file);  
  49.             // 将我们所得的二进制数据全部写入我们建好的文件中  
  50.             outputStream.write(data);  
  51.             // 关闭输出流  
  52.             outputStream.close();  
  53.         }  
  54.   
  55.     }  
  56.   
  57.     /** 
  58.      * 读取流文件的内容 
  59.      *  
  60.      * @param inputStream 
  61.      * @return 
  62.      * @throws Exception 
  63.      */  
  64.     public byte[] readInStream(InputStream inputStream) throws Exception {  
  65.         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
  66.         // 声明缓冲区  
  67.         byte[] buffer = new byte[1024];  
  68.         // 定义读取默认长度  
  69.         int length = -1;  
  70.         while ((length = inputStream.read(buffer)) != -1) {  
  71.             // 把缓冲区中输出到内存中  
  72.             byteArrayOutputStream.write(buffer, 0, length);  
  73.         }  
  74.         // 关闭输出流  
  75.         byteArrayOutputStream.close();  
  76.         // 关闭输入流  
  77.         inputStream.close();  
  78.         // 返回这个输出流的字节数组  
  79.         return byteArrayOutputStream.toByteArray();  
  80.     }  
  81. }  


 

0 0