27

How can I get the current computer's "Program Files" path with Java?

Stefanos Kargas
  • 10,547
  • 22
  • 76
  • 101
  • What is the use of gaining such an arcane and OS specific directory? What are you actually trying to achieve by knowing that information? – Andrew Thompson Jan 31 '11 at 14:18

4 Answers4

40

Simply by calling System.getenv(...)

System.getenv("ProgramFiles");

Notice it will only work in Windows environments, of course :-)

Riduidel
  • 22,052
  • 14
  • 85
  • 185
4

For 32 bit use:

    System.out.println(System.getenv("ProgramFiles(X86)")); 

For 64 bit use:

    System.out.println(System.getenv("ProgramFiles")); 
NiksD
  • 485
  • 1
  • 4
  • 8
4
System.getenv("%programfiles% (x86)"); 

for the 32-bit folder on 64-bit PC's.

Also, it works on any language in Windows Vista and newer. Calling either of the posted responses will work on any language installation, in fact.

narrowtux
  • 664
  • 7
  • 24
azvampyre
  • 57
  • 1
  • 1
2

Use the System.getenv() method:

public class EnvironmentVariableExample {

    public static void main(String[] args) {
        System.out.println(System.getenv("ProgramFiles"));
        System.out.println(System.getenv("MadeUpEnvVar"));
    }
}

If the variable doesn't exist, it will simply return null.

Michael
  • 7,348
  • 10
  • 49
  • 86