URL下载网页资源

要求:

给定一个图片的URL地址,如https://www.nwpu.edu.cn/images/logo2.png,使用Java的URL类,将该图片保存到本地磁盘上。

实现:

package downloadLogo;

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

/**
 * @author zxy
 * @version 1.0
 * Download Web Resources
 * Download NPUlogo
 */
public class download {
    public download() {
    }

    public static void main(String[] args) throws IOException {
        //1.下载地址
        URL url = new URL("https://www.nwpu.edu.cn/images/logo2.png");

        //2.链接到这个资源,用http链接
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

        //3.得到输入流
        InputStream inputStream = urlConnection.getInputStream();

        //4.下载到本地,同目录内名为"npulogo.png"
        FileOutputStream output = new FileOutputStream("npulogo.png");

        //5.设置缓冲区
        byte[] buffer = new byte[1024];

        int len;
        //6.从缓冲区中读,读到没有的时候写出去
        while((len = inputStream.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }

        //7.关闭,断开链接
        output.close();
        inputStream.close();
        urlConnection.disconnect();
    }
}

运行结果:

成功下载到通过目录下名为"npulogo.png"

URL下载网页资源_第1张图片

 URL下载网页资源_第2张图片

 

你可能感兴趣的:(java,servlet,jvm)