Java抓取网页图片并下载到本地(HTTP)
直接上代码:
package com.clzhang.sample.net; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; public class DownloadByHTTP { public static void download(String sourceURL, String destFilename) throws Exception { // 构造URL URL url = new URL(sourceURL); URLConnection con = url.openConnection(); con.setConnectTimeout(3 * 1000); // 输入流 InputStream is = con.getInputStream(); byte[] bs = new byte[1024]; int len; // 输出流 File file = new File(destFilename); OutputStream os = new FileOutputStream(file); while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } // 关闭链接 os.close(); is.close(); } public static void main(String[] args) throws Exception { String sourceURL = "http://www.hmting.com/data/attachment/forum/202204/01/175434p69b9ro9b71lqqpx.jpg.thumb.jpg"; String destFilename = "D:\\TDDOWNLOAD\\" + sourceURL.substring(sourceURL.lastIndexOf("/") + 1, sourceURL.length()); download(sourceURL, destFilename); } }