对接微信支付中开发过程中遇到的问题,(同事做过这块的对接,我想偷点懒...咳咳咳),下面是同事给的domo中的方法
public class WXPayConfigImp{
.
.
.
public static String CERT_PARTH = "C:\\Users\\test\\Desktop\\xxx.p12";//绝对路径
private final byte[] certData;
public WXPayConfigImp() throws Exception {
File file = new File(CERT_PARTH);
InputStream certStream = new FileInputStream(file);
this.certData = new byte[(int) file.length()];
certStream.read(this.certData);
certStream.close();
}
.
.
.
}
输出结果:
2718
实际使用时,xxx.p12文件存放到src/main/resources下,修改成如下所示:
public class WXPayConfigImp{
.
.
.
public static String CERT_PARTH = "../../../../xxx.p12";//相对路径
private final byte[] certData;
public WXPayConfigImp() throws Exception {
File file = new File(WXPayConfigImp.class.getResource(CERT_PARTH).getFile());
InputStream certStream = new FileInputStream(file);
this.certData = new byte[(int) file.length()];
certStream.read(this.certData);
certStream.close();
}
public static void main(String[] args) throws Exception {
WXPayConfigImp w = new WXPayConfigImp();
System.out.println(w.certData.length);
}
.
.
.
}
main方法输出结果:
2718
然而在启动项目使用时出现报错
java.io.FileNotFoundException: file:\D:\java\workspace\......\xxx-service.jar!\com\......\wxpay\xxx.p12 (文件名、目录名或卷标语法不正确。)
原因:WXPayConfigImp.class.getResource(CERT_PARTH).getFile()这个方法是专门用来加载非压缩/非Jar包文件类型的资源,而xxx.p12文件最终在jar包中,因此并没有读取到xxx.p12文件。
使用数据流形式去读取,如下所示:
public class WXPayConfigImp{
.
.
.
public static String CERT_PARTH = "xxx.p12";
private final byte[] certData;
public WXPayConfigImp() throws Exception {
InputStream certStream = this.getClass().getClassLoader().getResourceAsStream(CERT_PARTH);
this.certData = new byte[certStream.available()];
certStream.read(this.certData);
certStream.close();
}
public static void main(String[] args) throws Exception {
WXPayConfigImp w = new WXPayConfigImp();
System.out.println(w.certData.length);
}
.
.
.
}
main方法输出结果:
2718
启动项目使用时也是可用的。
如果有写的不对的地方,请大家多多批评指正,非常感谢!