请求远程服务器获取文件并拷贝至指定目录

请求远程服务器获取文件并拷贝至指定目录

今天接到一个需求需要同步其他项目的文件到本项目中,为了完成这个业务需求,用到了以下的方式来实现,仅供参考。

 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);
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值