How to work with environment variables?

Asked

Viewed 858 times

5

I am developing an application that works with files (save and upload) and have to work with system variables to determine where to save these files.

My question is: Is there any way to use variables independent of the operating system? If so, how should I proceed. For example, I know that if I put a variable caminho, for example in windows as follows:

%caminho%\algum_dir\algum_arquivo.exemplo

He will convert %caminho% for the string contained in this variable. The same goes for Linux, only using $caminho. So, in short, I wanted to know if it is possible to use some kind of nomenclature for the program to detect an environment variable, which has a name defined by me, independent of the OS, since the program will be in Java.

1 answer

4


I think what you want is the method getenv(). He is responsible for reading the environment variables and takes care of the specifics of the operating systems. I removed this code from official tutorial:

import java.util.Map;

class Main {
    public static void main (String[] args) {
        Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) System.out.format("%s=%s%n", envName, env.get(envName));
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I imagine you can get what you want from there. Documentation from Map. Essentially the key is the variable and the value is its content.

Browser other questions tagged

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