获取资源Sping Boot Java

iq0todco  于 2022-10-30  发布在  Java
关注(0)|答案(2)|浏览(127)

如何从文件夹resources/key中获取资源?
我是这样做的:

String Key = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("key/private.pem").toURI())));

当我把项目构建到一个jar中时,它不起作用。所以我在寻找另一种方法来做这件事。你能告诉我如何获得资源吗?

private PublicKey getPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {

        String key = getPublicKeyContent().replaceAll("\\n", "")
                .replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));

        KeyFactory kf = KeyFactory.getInstance("RSA");

        return kf.generatePublic(keySpec);
      }

      private PrivateKey getPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {

        String key = getPrivateKeyContent().replaceAll("\\n", "")
                .replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "");

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));

        KeyFactory kf = KeyFactory.getInstance("RSA");

        return kf.generatePrivate(keySpec);
      }
qvtsj1bj

qvtsj1bj1#

试试这个使用spring framework核心和util包的util方法。

public static String getResourceFileContent(String resourcePath) {
        Objects.requireNonNull(resourcePath);
        ClassPathResource resource = new ClassPathResource(resourcePath);
        try {
            byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
            return new String(bytes);
        } catch(IOException ex) {
            log.error("Failed to parse resource file : " + resourcePath, ex);
        }
    }
pxq42qpu

pxq42qpu2#

您应该将/添加到资源路径中,并使用InputStream

public class Foo {

    public static byte[] readResourceFile(String path) throws IOException {
        if (path.charAt(0) != '/')
            path = '/' + path;

        try (InputStream in = Foo.class.getResourceAsStream(path)) {
            return IOUtils.toByteArray(in);
        }
    }

}

请记住,当您构建jar文件时,resource将被复制到jar文件的根目录下。
这是来源:

Foo
|--> src
      |--> main
      |     |--> java
      |     |     |--> com
      |     |           |--> stackoverflow
      |     |                  |--> Foo.java
      |     |--> resources
      |     |     |--> key
      |                 |--> private.pem
      |--> test

这是一个foo.jar文件

foo.jar
|--> META_INF
|--> com
|     |--> stackoverflow
|           |--> Foo.class
|--> key
      |--> private.pem

foo.jar的根是/,所以资源的完整路径是/key/private.pem

相关问题