Wednesday, July 10, 2013

Determine windows is 32 or 64 bit using Java Programatically

import com.sun.servicetag.SystemEnvironment;

"os.arch" environment may not give you the correct architecture.
Let's try out.

public class OSArchLies {
  
  public static void main(String[] args) {
    
    // Will say "x86" even on a 64-bit machine using a 32-bit Java runtime
    SystemEnvironment env =   SystemEnvironment.getSystemEnvironment();
    final String envArch = env.getOsArchitecture();
    
    // The os.arch property will also say "x86" on a 64-bit machine using a 32-bit runtime
    final String propArch = System.getProperty("os.arch");
    
    System.out.println( "getOsArchitecture() says => " + envArch );
    System.out.println( "getProperty() says => " + propArch );
    
  }

}

Environment: Windows 7, 64 bit os, 32 bit JVM

Output:
getOsArchitecture() says => x86
getProperty() says => x86


Try this approach,

public class Windows32Or64bitCheck {

public static void main(String[] args) {
        boolean is64bit = false;
       
        System.out.println(System.getProperty("sun.arch.data.model", "?"));
        System.out.println(System.getProperty("os.arch")); // Please note, the os.arch property will only give you the architecture of the JRE, not of the underlying os. 
        System.out.println(System.getenv("ProgramFiles(x86)"));
        
        if (System.getProperty("os.name").contains("Windows")) {
            is64bit = (System.getenv("ProgramFiles(x86)") != null);
        } else {
            is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
        }
        System.out.println("is64bit: " + is64bit);
 }

}

Environment: Windows 7, 64 bit os, 32 bit JVM

Output:
32
x86
C:\Program Files (x86)
is64bit: true


This is the only way which i could find from Java( Using native C, there is a better and accurate way to achieve this) 

Using C, please follow below link

Other way I have learned recently, using Windows wmi service calls.
>  wmic OS get OSArchitecture


C:\Users\KH1205>wmic OS get OSArchitecture
OSArchitecture
64-bit

Try to run this command programatically using Java Runtime process.

No comments:

Post a Comment