Getting Relative Path Of File Stored in WEB-INF?

725 Views Asked by At

I'm somewhat of a beginner learning Java.

I'm having trouble with finding the path-file

readPublicKeyFromFile("C:\Users\myname\workspace\MyProject\WebContent\WEB-INF\Config\My_Public.key");

for one of my methods:

public byte[] encryptData(String data) throws IOException {


        byte[] dataToEncrypt = data.getBytes();
        byte[] encryptedData = null;

        try
        {
            PublicKey pubKey = readPublicKeyFromFile("C:\Users\myname\workspace\MyProject\WebContent\WEB-INF\Config\My_Public.key");
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            encryptedData = cipher.doFinal(dataToEncrypt);
            System.out.println("Encrypted Data: " + encryptedData);
        }
        catch (IOException | NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e)
        {
            e.printStackTrace();
        }   

        System.out.println("--ENCRYPTION COMPLETED--");
        return encryptedData;
    }

The file My_Public.key is stored in C:\Users\myname\workspace\MyProject\WebContent\WEB-INF\Config\My_Public.keyin my computer system and in my Eclipse Project hierarchy it is as follows:

> MyProject
  > WebContent
     > WEB-INF
        > Config
           > My_Public.key
     > META-INF

It works fine if I use relative path "C:/Users/myname/workspace/MyProject/WebContent/WEB-INF/Config/My_Public.key. But I don't want to use the relative path C:/Users/myname/... since it will not work when I upload my Java web-app online.

I try using some path like:

readPublicKeyFromFile(getServletContext().getRealPath("/WebContent/WEB-INF/Config/My_Public.key"));

But it gives me this error:

java.io.FileNotFoundException: WebContent\WEB-INF\Config\My_Public.key (The system cannot find the path specified)

How can I read from my file:

> MyProject
      > WebContent
         > WEB-INF
            > Config
               > My_Public.key //How can I read from this file in the correct path?
         > META-INF
1

There are 1 best solutions below

1
On

Use the following

readPublicKeyFromFile(getServletContext().getRealPath("/WEB-INF/Config/My_Public.key"));