2014-06-17 50 views
1

我用以下問題的答案,以確定系統位版本,其中精除在Mac OSX: How can I check the bitness of my OS using Java?? (J2SE, not os.arch)爪哇 - 確定操作系統位版本

String arch = System.getenv("PROCESSOR_ARCHITECTURE"); 
String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432"); 

String realArch = arch.endsWith("64") 
        || wow64Arch != null && wow64Arch.endsWith("64") 
         ? "64" : "32"; 

最後一行(realArch)給了我一個NPE在Mac上,你有什麼想法我可以解決它,我也得到正確的位版本在Mac上呢?

UPDATE:

我讀答案錯了,對不起那個。它工作正常的Windows,Mac OSX和Ubuntu的這個小變化:

String realArch = System.getProperty("os.arch").endsWith("64") 
      ? "64" : "32"; 

    if (System.getProperty("os.name").startsWith("Windows")) { 
     String arch = System.getenv("PROCESSOR_ARCHITECTURE"); 
     String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432"); 
     realArch = arch.endsWith("64") 
       || wow64Arch != null && wow64Arch.endsWith("64") 
       ? "64" : "32"; 
    } 

回答

1

您所使用的環境變量是操作系統相關的,所以當然,他們不會在所有平臺上工作。嘗試使用OS X以下:

public class Test { 

    public static void main(String[] args) { 
     System.out.println("Is 64Bit? " + is64BitMacOS()); 
    } 



    public static boolean is64BitMacOS() { 
     java.io.BufferedReader input = null; 
     try { 
      String line; 
      Process proc = Runtime.getRuntime().exec("sysctl hw"); 
      input = new java.io.BufferedReader(new java.io.InputStreamReader(proc.getInputStream())); 
      while ((line = input.readLine()) != null) { 
       if (line.length() > 0) { 
        if ((line.indexOf("cpu64bit_capable") != -1) && (line.trim().endsWith("1"))) { 
         return true; 
        } 
       } 
      } 
     } catch (Exception ex) { 
      System.err.println(ex.getMessage()); 
     } finally { 
      try { 
       input.close(); 
      } catch (Exception ex) { 
       System.err.println(ex.getMessage()); 
      } 
     } 

     return false; 
    } 
} 
+0

我覺得我讀的其他問題錯誤的答案。你知道System.getProperty(「os.arch」)是否適用於除windows之外的所有系統? – user2693017

+0

@ user2693017'os.arch'爲您提供_JVM_而非OS的位數。如果你想知道Java是否是64位,那麼是的,使用'os.arch'。如果你需要知道底層操作系統的位數(不太可能,但也許如果你說你正在使用一些本地庫),那麼使用你的答案和我的答案。 – whiskeyspider

+0

@ user2693017而'os.arch'適用於** ALL **平臺,包括Windows。 – whiskeyspider

1

你是不是檢查拱爲空:

試試這個:

String realArch = arch != null && arch.endsWith("64") || wow64Arch != null && wow64Arch.endsWith("64") ? "64" : "32";