JAVA–根据Url下载文件至本地(输出IO文件)
public static String downloadImgToSys(String filePath,String fileName,String url){
try{
System.out.print("开始下载"+url+"资源\n");
URL uploadUrl = new URL(url);
HttpURLConnection httpUrl = (HttpURLConnection) uploadUrl.openConnection();
httpUrl.connect();
httpUrl.getInputStream();
InputStream inputStream = httpUrl.getInputStream();
byte[] getData = readInputStream(inputStream);
File saveDir = new File(filePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+File.separator+fileName+".png");
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if(fos!=null){
fos.close();
}
if(inputStream!=null){
inputStream.close();
}
return "";
} catch (Exception ex){
System.out.print("文件下载出错:"+ex.getMessage()+"\n");
return "";
}
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}