JAVA实现 图片或文件下载功能示例代码
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class TestDownload {
public static void main(String args[]) throws Exception {
TestDownload.getImagesNew("https://zszhan.cn/upload/image/20210630/zip/183904.png", "D:\\temp\\a.png");
}
/**
* @param urlPath 图片路径
* @throws Exception
*/
public static void getImagesNew(String urlPath, String fileName) throws Exception {
URL url = new URL(urlPath);// :获取的路径
// :http协议连接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(6 * 10000);
if (conn.getResponseCode() < 10000) {
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] buffer = new byte[2048];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
inputStream.close();
System.out.println(1111);
}
}
}