我使用以下问题的答案来确定系统位版本,除了在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)在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";
}
答案 0 :(得分: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;
}
}
答案 1 :(得分:1)
您没有检查arch是否为null:
试试这个:
String realArch = arch != null && arch.endsWith("64") || wow64Arch != null && wow64Arch.endsWith("64") ? "64" : "32";