请求远程服务器获取文件并拷贝至指定目录
今天接到一个需求需要同步其他项目的文件到本项目中,为了完成这个业务需求,用到了以下的方式来实现,仅供参考。
public void syncPic()throws Exception{
// 获取远程服务地址
String remotoUrl = ResourceBundle.getBundle("propName").getString("propUrl");
if(StringUtils.isBlank(remotoUrl)){
logger.info("配置文件未配置远程服务器地址");
return;
}
// 获取远程数据库的文件数据(视你具体情况而定)
List<String> strList = romoteMapper.findList();
URL urlfile = null;
HttpURLConnection httpUrl = null;
for (String item : strList ) {
FileOutputStream fos = null;
String fileUrl = "";
try {
// 获取图片路径
String url = item.getFileUrl;
urlfile = new URL(remotoUrl + url);
httpUrl = (HttpURLConnection) urlfile.openConnection();
httpUrl.connect();
// inputStream 转化为byte 数组
byte[] buffer = input2byte(httpUrl.getInputStream());
String targetPath = filePath + url;
File file = new File(filePath + url.substring(0,url.lastIndexOf("/")));
if (!file .exists()) {
file .mkdirs();
}
// 文件写入到指定目录
fos = new FileOutputStream(targetPath);
fos.write(buffer);
fileUrl = targetPath;
httpUrl.disconnect();
}catch (Exception e){
logger.error("文件路径不存在:" + item.getFileUrl);
}finally {
try {
if (fos != null) fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 写入本机数据库
if(StringUtils.isNotBlank(fileUrl)) {
Map<String, Object> insertData = new HashMap<>();
insertData.put("column1", fileUrl);
insertData.put("column1", value1);
create(insertData);
}
}
}