java学习记录14-通过url下载网络资源

生态人

关注

阅读 65

2022-04-01

java学习记录

public class GetUrl {
    public static void main(String[] args) throws Exception {
//        要下载的url      要下载的资源地址
        URL url = new URL("http:xxx.xxx.xxx");
//        连接这个资源 HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//        得到流
        InputStream inputStream = urlConnection.getInputStream();
//                                                  下载后的命名
        FileOutputStream fos = new FileOutputStream("xxx.txt");
        byte[] buffer = new byte[1024];
        int len;

        while((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();
    }
}

精彩评论(0)

0 0 举报