Java网络编程---URL下载网络资源

徐一村

关注

阅读 140

2022-02-17

public class UrlDemo {
    public static void main(String[] args) throws Exception{
        //1.创建URL对象
        URL url = new URL("...");
        //2.连接资源 Http
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //3.获取流
        InputStream is = connection.getInputStream();
        //4.下载到本地
        FileOutputStream fos = new FileOutputStream(new File("jay.jpg"));
        byte[] bytes = new byte[1024];
        int len;
        while ((len=is.read(bytes))!=-1){
            fos.write(bytes,0,len);
        }
        //5.关闭
        fos.close();
        is.close();
        connection.disconnect();


    }
}

精彩评论(0)

0 0 举报