直接上代码:
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);
}
}
Original: https://www.cnblogs.com/nayitian/p/16276529.html
Author: 那些年的事儿
Title: Java抓取网页图片并下载到本地(HTTP)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/538802/
转载文章受原作者版权保护。转载请注明原作者出处!