Java-URL


# URL下载网络资源:

package com.chengmengdui.lesson1;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class URL01 {
    public static void main(String[] args) throws IOException {
        //1.下载地址
        URL url = new URL("https://img11.360buyimg.com/n1/s450x450_jfs/t1/131699/27/12929/65603/5f8d4210E80b0f535/8059416fb6258cb2.jpg");

        //2.链接到这个资源HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fos= new FileOutputStream("cmd.jpg");
        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);//写出这个数据

        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();



    }
}

相关