May 4, 2021
By: Syh

clojure与java交互打包问题

  1. -noverify
  2. 引入三方jar
  3. 读取resource文件

-noverify

通过使用 -noverify 参数,关闭 Java 字节码的校验功能

在clojure 项目 project.clj配置文件中添加 -noverify

:project/dev {:jvm-opts ["-Dconf=dev-config.edn" "-noverify"]}

来关闭java字节码校验功能

引入三方jar

以下都是项目未达成jar包前都正常运行

  1. 引入.java 文件

    • 在java文件夹创建.java文件

    • 在project.clj配置文件引入

      :java-source-paths ["src/java"]
      
    • 在.clj 引入即可

      (:import (jspaypos JSPayPosUtil))
      
  2. 引入三方jar

    • 在resoutces下存放要引入的三方jar包

    • 在project.clj配置文件引入

      :resource-paths ["resources" "resources/jars/xxx.jar"]
      

在打成jar包后会导致找不到.jar包

  1. 将要引入的三方jar,手动放到你的本地maven仓库

    mvn install:install-file -DgeneratePom=true -DcreateChecksum=true \
    -Dpackaging=jar -Dfile=resources/jars/BASE64Decoder.jar -DgroupId=com.slzx.third \
    -DartifactId=BasE64Decoder -Dversion=1.0
    
  2. 引入

    [com.slzx.third/BasE64Decoder "1.0"]
    
  3. -noverify

    • 运行jar 以上添加jvm-opts不起作用

    • 运行jar 用一下方式来添加java-opts 的参数

      java -noverify -jar xxx.jar
      

读取resource文件

在读取resource文件时会导致java.io.FileNotFoundException 找不到文件问题

在这里问题 一定要用流,流,流来读取resource里面的文件,不要像我傻愣愣的一开始要找路径来读取

文件时读不到的

  1. 用很多种找路径的方法!

    String path2 = JSPayPosUtil.class.getResource("/assets/hongchuang.pfx").getPath();
    System.out.println("getResource``"+path2);
    URL resource = JSPayPosUtil.class.getClassLoader().getResource("assets/hongchuang.pfx");
    System.out.println("getClassLoader``url```"+resource);
    String path = JSPayPosUtil.class.getClassLoader().getResource("assets/hongchuang.pfx").getPath(); System.out.println("getClassLoader``string"+path);
    String absolutePath = new File("").getAbsolutePath();
    System.out.println("" + absolutePath);
    String absolutePathpfx = new File("hongchuang.pfx").getAbsolutePath();
    System.out.println("```hongchuang.pfx" + absolutePathpfx);
    String absolutePathcer = new File("jschina.cer").getAbsolutePath();
    System.out.println("`jschina.cer" + absolutePathcer);
    String absolutePath2 = new File("/hongchuang.pfx").getAbsolutePath();
    System.out.println("hongchuang.pfx" + absolutePath2);
    String property = System.getProperty("user.dir");
    

    以上可以回去到路径但是不好使,还是获取不到文件!

    1. (io/input-stream (io/resource "assets/hongchuang.pfx"))

      • 文档 说的很清楚要用

        If you need to copy a binary file from a running JAR (or WAR), don't call slurp as it will try and decode the file. Instead, extract similarily to:
        
        (with-open [in (io/input-stream (io/resource "file.dat"))] ;; resources/file.dat
            (io/copy in (io/file "/path/to/extract/file.dat"))))
        
        • (io/resource "assets/hongchuang.pfx")会返回一个java.net.URL 不要再傻傻的返回路径

        • (io/input-stream (io/resource "assets/hongchuang.pfx")) 返回一个java.io.BufferedInputStream可以读到文件

参考博客

Tags: clojure