欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java URL下载网络资源

程序员文章站 2022-05-05 20:42:17
...
import sun.net.www.protocol.http.HttpURLConnection;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class URLDown {
    public static void main(String[] args) throws Exception{
        //1. 下载地址
        URL url = new URL("http://localhost:8080/shisan/look.txt");

        //2. 连接到这个资源
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("m1.mp4");

        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);//写出这个数据
        }

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

    }
}
相关标签: url