下载文件
spring resttemplate下载文件
String suffix = url.substring(url.lastIndexOf("."));
if(CheckUtils.isEmpty(filename)) {
filename = url.substring(url.lastIndexOf("/") + 1);
} else if(!CheckUtils.isEmpty(suffix)) {
filename = filename.substring(0, filename.lastIndexOf("."));
filename += suffix;
}
OutputStream outputStream = null;
byte[] result = restTemplate.getForObject(url, byte[].class);
File file = new File(downloadLocation, filename);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
outputStream = new FileOutputStream(file);
outputStream.write(result);
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
网友评论