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

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(); 
    } 
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭