0

echo $MY_FILE prints "/path/to/some/file"

System.out.println(System.getenv("MY_FILE")); prints null

Additionally, when i print JAVA_HOME (from Eclipse), i too get null. From the shell it echoes /Library/Java/Home

Not sure whether this is relevant, but system i am running is a mac

Any hints?

James Raitsev
  • 92,517
  • 154
  • 335
  • 470

3 Answers3

0

You likely have not exported the environment variable. In most shells, variables declared in the shell are not exported into the environment of subprocesses unless you do so explicitly, either like this:

export MY_HOME=/somewhere/over/the/rainbow

Or when invoking the program:

MY_HOME=/somewhere/over/the/rainbow java com.example.MyApplication

Also keep in mind that the environment is not global, so changes you make to the environment only affect that process and its subprocesses. If you want to affect the environment of all processes on your system, this has to be configured specially. In most cases, exporting in the shell is what you want.

Jeremy Roman
  • 16,137
  • 1
  • 43
  • 44
0

First try to access a system variable not created by you say

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

If the above work, try rebooting your VM

It appears that environment variable are in some sort of cache, and rebooting is one method to refresh it.

mbh
  • 3,302
  • 2
  • 22
  • 24
0

The way to access an environment variable is precisely the way you're aware of. That code works just fine, and the results you receive accurately tell you about the execution environment of the JVM that you're asking the questions of. So,

  1. Environment variables are not 'system variables': they don't have system-scope; changing them in a new terminal will not change them in the process that launches terminals, etc.

  2. They are held by an OS process, and are copied to children of that process. So, children also do not change the environment variables of their parents, when they change their own.

  3. If you launch Eclipse, and then set environment variables in .profile or whatever, and then JVMs launched from Eclipse do not reflect these settings, then you know that Eclipse does not launch a shell that reads your .profile before launching the JVM; it may invoke the shell so that it doesn't read .profile, it may invoke another shell altogether, it may launch the JVM directly, without involving a shell.

  4. If you launch Eclipse after setting those variables, and see the same behavior, then you've learned the same of the process that launches Eclipse.

  5. If you reboot after setting those variables, and see the same behavior, then you've learned the same about your windowing environment.

You can't learn that you're "doing it wrong" when you ask for the values of environment variables in Java, as you're actually doing it right.

You can explore your environment with System.getenv()

Julian Fondren
  • 5,459
  • 17
  • 29