Include file in Java project

Asked

Viewed 127 times

0

I have a code that runs routines inside Linux servers and access using public keys. When the project is on my pc (development), everything works because in the code I specify the location of the key that is on my machine, however when generating a jar (package for store) and running on another computer, the program does not find this key.

I already put the key inside the src/meProject folder and made the reference to the file and locally it worked, but on another machine not.

I researched getresources but I still couldn’t.

I refer to the file as any string:

String privateKey = "Diretorio\id_dsa.ppk";

What would be the correct way to attach this key to my project so that it runs on any machine?

1 answer

1

You are making reference to the directory via hard coded, this is not a good idea, in different environments this may not work, for example, Windows uses the so-called "backslash" to separate directories, while linux uses the "normal toolbar".

Yaml

The good practice in this case is the use of a configuration file, my preference is the yaml, some languages, like python, have packages for parse yaml, I don’t know if you have in java, but has this tutorial.

Example of a yaml configuration file:

linux:
  privateKey: /home/user/keys/id_dsa.ppk  
  ...

windows:
  privateKey: c:\path\keys\id_dsa.ppk  

So in your app just identify the environment and read the privatekey variable from the correct key (linux or windows).

Environment variable:

Another option within good practices is the use of environment variables. Your app would have to read an environment variable that points to the file path, example of creating variables:

Creating environment variable in linux:

export PKEY=/home/user/keys/id_dsa.ppk

To create environment variables in windows, see this link.

Obs.:
Using environment variables may seem easier for the developer side, but in my opinion the configuration file is safer and more flexible.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.