@Test
void downloadFile() throws Exception{
String savedir = "G:/pic"; // 要保存的文件夹
String fileUrl = "http://img.netbian.com/file/2022/0716/small002117VeofM1657902077.jpg";
URL url = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.connect();
BufferedInputStream br = new BufferedInputStream(conn.getInputStream());
File f = new File(savedir);
if(!f.exists()){ f.mkdirs(); }
FileOutputStream fos = new FileOutputStream(savedir + fileUrl.substring(fileUrl.lastIndexOf("/")));
byte[] buf = new byte[1024];
int size = 0 ;
while((size = br.read(buf) )!= -1){
fos.write(buf,0,size);
}
br.close();
fos.close();
conn.disconnect();
}
注意 : 第十行要用
f.mkdirs()
,不要用f.mkdir()
,不然要创建多级目录时程序会报错