[英]Java - Determine OS bit version
我使用以下問題的答案來確定系統位版本,該版本在mac osx上還可以正常工作: 如何使用Java檢查操作系統的位? (J2SE,不是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)在Mac上為我提供了NPE,您是否知道如何解決該問題,我也在Mac上獲得了正確的版本?
更新:
我讀錯了答案,對此感到抱歉。 進行以下更改,即可在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";
}
您所使用的環境變量取決於操作系統,因此它們當然不能在所有平台上都起作用。 對於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;
}
}
您不檢查arch是否為null:
嘗試這個:
String realArch = arch != null && arch.endsWith("64") || wow64Arch != null && wow64Arch.endsWith("64") ? "64" : "32";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.