一、前言
一个简单的java批量下载图片示例,速度有些慢,不过勉强可用。
二、结构
三 、代码
main
package lyrics
.download
;
import java
.io
.IOException
;
import lyrics
.download
.Service
.DownloadService
;
public class DownloadTest {
public static void main(String
[] args
) {
DownloadService downloadService
= new DownloadService();
String url
= "https://picsum.photos/300/150/?image=";
String path
= "D:\\picture\\";
for(int i
= 0; i
<100;i
++) {
try {
if(!downloadService
.download(url
+i
, path
)) {
System
.out
.println("Download failed!");
}
} catch (IOException e
) {
e
.printStackTrace();
}
System
.out
.println("pciture "+i
+" Download successful!");
}
}
}
下载服务
package lyrics
.download
.Service
;
import java
.io
.File
;
import java
.io
.FileOutputStream
;
import java
.io
.IOException
;
import java
.io
.InputStream
;
import java
.net
.HttpURLConnection
;
import java
.net
.URL
;
public class DownloadService {
public boolean download(String uri
, String path
) throws IOException
{
URL url
= new URL(uri
);
HttpURLConnection conn
= (HttpURLConnection
) url
.openConnection();
conn
.setRequestMethod("GET");
conn
.setUseCaches(false);
conn
.setConnectTimeout(5000);
conn
.connect();
String fileName
= uri
.substring(uri
.lastIndexOf("=") + 1)+".jpg";
File file
= new File(path
+ "\\" + fileName
);
if(!file
.exists()) {
file
.createNewFile();
}
FileOutputStream fileOutputStream
= new FileOutputStream(file
);
InputStream input
= conn
.getInputStream();
int len
= 0;
byte[] data
= new byte[1024];
while((len
= input
.read(data
))!=-1) {
fileOutputStream
.write(data
, 0, len
);
}
fileOutputStream
.close();
input
.close();
return true;
}
}
四、测试
五、最后
晚安,代码如有建议,请不吝赐教,也请大家多多包涵!!