您的位置:首页 > 编程语言 > Java开发

JAVA编写一个程序从网上下载一张图片

2017-05-17 16:40 351 查看
package com.capinfotech.net; 

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.URL; 

public class ImageRequest { 

    public static void main(String[] args) throws IOException { 
        URL url = new URL("https://gss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/album/w%3D2048/sign=1bb39918cdbf6c81f7372be88806b035/9345d688d43f879423f3355ed31b0ef41bd53ab5.jpg"); 
        HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
        InputStream inputStream = conn.getInputStream();   //通过输入流获得图片数据 
        byte[] getData = readInputStream(inputStream);     //获得图片的二进制数据 

        File imageFile = new File("tupian.jpg");   
        FileOutputStream fos = new FileOutputStream(imageFile);    
        fos.write(getData); 
        fos.close(); 

        System.out.println(" read picture success"); 
    } 

    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(); 
    } 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐