How can I set a filepath in java by using Environmental Variables from windows?

I am trying to create a new file inside of the appdata directory, but none of the environmental varibles that I am using with the classpath are working.

I want this program to be runnable on more than just my local machine, so I dont want to hardcode the values in there, which is why I am using these variables.

If I try the command

FileOutputStream outputStream = new FileOutputStream(new File("%HOMEDRIVE%//chromedriver.exe"));

or

FileOutputStream outputStream = new FileOutputStream(new File("%AppData%\Local\Temp"));

Both of them give the error

%HOMEDRIVE%chromedriver.exe (The system cannot find the path specified)

Any advice?

Answer

You could use java.io.tmpdir like,

System.out.println(System.getProperty("java.io.tmpdir"));

Another option, is to use File.createTempFile(String, String) which will create a temporary file in the system temp directory. If you just want to access an environment variable, you can do that with something like

System.out.println(System.getenv("HOMEDRIVE"));

(if you want to access %HOMEDRIVE%). Note: On *nix-like systems, the above would access the environment variable $HOMEDRIVE.

Leave a Reply

Your email address will not be published. Required fields are marked *