项目根路径读取写入

前段时间做的功能,有些技术点记录下,

  1. //获取类加载的根路径
    String rootPath=this.getClass().getResource("/").getPath();
    根路径即画圈部分.png

    2.httpclient模拟表单上传附件
    需要实现的目标格式.png

    具体实现:
                HttpPost httpPost = new HttpPost(reqUrl);
                httpPost.setConfig(config);
                ContentType contentTypeUpload = ContentType.create("multipart/form-data");

                MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                multipartEntityBuilder.setBoundary("boundary--");
                multipartEntityBuilder.setContentType(contentTypeUpload);

                ContentType contentTypeMeta = ContentType.create("application/json");
                multipartEntityBuilder.addTextBody("meta",params,contentTypeMeta);
                //判断类型
                ContentType contentTypeImage = ContentType.create("image/jpeg");
                if (StringUtils.isNotBlank(fileName)){
                    String filename=fileName;
                    if (filename.endsWith(".png")) {
                        contentTypeImage = ContentType.create("image/png");
                    }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                        contentTypeImage = ContentType.create("image/jpeg");
                    }else if (filename.endsWith(".gif")) {
                        contentTypeImage = ContentType.create("image/gif");
                    }else if (filename.endsWith(".ico")) {
                        contentTypeImage = ContentType.create("image/image/x-icon");
                    }
                }

                if (StringUtils.isNotBlank(fileName)){
                    multipartEntityBuilder.addBinaryBody("file",bytes,contentTypeImage,fileName);
                }

                HttpEntity httpEntity=multipartEntityBuilder.build();
                httpPost.addHeader("Authorization",token);
                httpPost.setHeader("Accept", "*/*");

                httpPost.setEntity(httpEntity);
                CloseableHttpResponse response = httpClient.execute(httpPost);

注:之前为了看到上传数据的结果,不小心打印了entity,只能上传很小的图片,稍大一点的上传图片结果出现了Content length is too long,找了老长时间原因。后来在源码中找到了报错原因,去掉调用此方法即可解决。


若打印entity内容有可能会抛异常.png

3.加载配置文件

   public static  PropertiesConfiguration config;
   //PostConstruct在容器启动的时候加载,且仅加载一次
   @PostConstruct
   public static void init() {
       try {
           log.info("加载配置信息--开始");
           config = new PropertiesConfiguration("bank/certificate/XXXX/certificate.properties");
           log.info("加载配置信息--完成");
       } catch (Exception e) {
           log.error("初始化基础信息失败!:",e);
       }
   }

配置文件:

#平台证书序号
plantcer_XXXXX=bank/certificate/XXXXX/wenjianjia/zhengshuwenjian.pem

在静态方法中获取本地路径

            //平台证书路径
            String relativeFilePath= WeChatCertificateConfigUtils.config.getString("plantcer_"+merchantId);
            // 读取本机存放的PKCS8证书文件
            String currentPath = Thread.currentThread().getContextClassLoader().getResource(cerPath).getPath();
            X509Certificate cert = PemUtil.loadCertificate(new FileInputStream(currentPath));

载入证书方法:

public static X509Certificate loadCertificate(InputStream inputStream) {
    try {
      log.info("---loadCertificate-----");
      CertificateFactory cf = CertificateFactory.getInstance("X509");
      X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
      cert.checkValidity();
      return cert;
    } catch (CertificateExpiredException e) {
      throw new RuntimeException("证书已过期", e);
    } catch (CertificateNotYetValidException e) {
      throw new RuntimeException("证书尚未生效", e);
    } catch (CertificateException e) {
      throw new RuntimeException("无效的证书", e);
    }
  }
获取内容的位置.png

4.将证书保存在本地

private void saveCertificate(List cert,String outputFilePath) throws IOException {
        //获取类加载的根路径
        String rootPath=this.getClass().getResource("/").getPath();
        String pkfp=StringUtils.join(rootPath,outputFilePath);
        File file = new File(pkfp);
        file.mkdirs();

        for (PlainCertificateItem item : cert) {
            String outputAbsoluteFilename = file.getAbsolutePath() + File.separator + "wechatpay_" + item.getSerialNo() + ".pem";
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(outputAbsoluteFilename), StandardCharsets.UTF_8))) {
                writer.write(item.getPlainCertificate());
            }

            log.info("save cert file absolute path = {}" , outputAbsoluteFilename);
        }
    }

你可能感兴趣的:(项目根路径读取写入)