Home > Software engineering >  Get Resource Spring Boot Java
Get Resource Spring Boot Java

Time:10-29

How to get resource from folder resources/key?

I did like this:

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

And it doesn't work when I build the project into a jar. So I'm looking for another way to do this. Can you please tell me how to get the resource?

    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);
      }

CodePudding user response:

Try this util method which uses spring framework core and util packages.

    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);
        }
    }

CodePudding user response:

You should add / to the resource path and use 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);
        }
    }

}

Remember that when you build a jar file, the resource will be copied to the root of the jar file.

This is the sources:

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

This is a foo.jar file

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

And the root of the foo.jar is a /. So the full path to the resouces is /key/private.pem.

  • Related