Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set environment variables for Java

I have inserted the following lines in .bash_profile

export GOOGLE_APPLICATION_CREDENTIALS=/Users/jun/Downloads
export PATH=$PATH:GOOGLE_APPLICATION_CREDENTIALS

and the changes did take effect

enter image description here

However, when I try to access the environment variable with the following method

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

The result is NULL

Why is that?

Note: The application is ran with Eclipse.

like image 520
JLT Avatar asked Apr 16 '18 09:04

JLT


People also ask

Do I need to set environment variables in Java?

Java For Testers Before running Java programs on your machine you need to set two environment variables namely, PATH − The path environment variable is used to specify the set of directories which contains execution programs.

What environment variables should be set for Java path?

The path is the most important environment variable of the Java environment which is used to locate the JDK packages that are used to convert the java source code into the machine-readable binary format. Tools like javac and java can be used by setting the path.

What is JAVA_HOME environment variable?

JAVA_HOME is an operating system (OS) environment variable which can optionally be set after either the Java Development Kit (JDK) or the Java Runtime Environment (JRE) is installed. The JAVA_HOME environment variable points to the file system location where the JDK or JRE was installed.


Video Answer


2 Answers

I suspect that the environment variable you're setting in your .bash_profile isn't getting picked up.

If you're running from Eclipse, you need to set environment variables manually on the Environment tab in the Run Configuration.

Go to Run -> Run Configurations..., find or create the run configuration for your app under Java Applications, go to the Environment tab and add your desired environment variables there.

Click the Run button and your program should print the environment variable as expected.

like image 87
Azquelt Avatar answered Oct 30 '22 12:10

Azquelt


To set an environment variable, use the command "export varname=value", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces.

You can set an environment variable permanently by placing an export command in your Bash shell startup script "~/.bashrc" (or "~/.bash_profile", or "~/.profile") of your home directory; or "/etc/profile" for system-wide operations.

If you use eclipse then you can set argument which used by jvm while running java program as

click right click on project name click Run as ----> Run Configuration --> click on argument tab from left upper corner.

like image 37
Abhijeet Kale Avatar answered Oct 30 '22 12:10

Abhijeet Kale