如何使用Java确定Windows的32位或64位架构?

Mat*_*hew 54 java windows 64-bit x86

如何使用Java确定Windows的32位或64位架构?

Boo*_*ean 74

我并不完全相信读取os.arch系统变量.虽然它在用户在64位系统上运行64位JVM时有效.如果用户在64位系统上运行32位JVM,则它不起作用.

以下代码适用于正确检测Windows 64位操作系统.在Windows 64位系统上,将设置环境变量"Programfiles(x86)".它不会在32位系统上设置,java会将其读为null.

boolean is64bit = false;
if (System.getProperty("os.name").contains("Windows")) {
    is64bit = (System.getenv("ProgramFiles(x86)") != null);
} else {
    is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
}
Run Code Online (Sandbox Code Playgroud)

对于Linux或Solaris或Mac等其他操作系统,我们也可能会看到此问题.所以这不是一个完整的解决方案.对于mac,您可能很安全,因为Apple锁定JVM以匹配操作系统.但Linux和Solaris等......他们仍然可以在64位系统上使用32位JVM.所以谨慎使用它.

  • “我并不完全相信阅读 `os.arch` 系统变量。” 这种行为的原因是,例如 [JNI](https://en.wikipedia.org/wiki/Java_Native_Interface) 对于了解 **[JVM](https://en.wikipedia.org/ wiki/Java_virtual_machine)**,而不是底层操作系统(如果您需要将自己的平台相关共享库加载到 Java 代码中,则它们需要与 JVM 相同)。 (2认同)
  • +1经过相当多的研究后,我将使用它.但我很好奇,在这台机器上(Windows 8.1 64位)环境变量`ProgramFiles(x86)`没有列在"这台PC"/属性/高级系统设置/环境变量下,但是`System.getenv("ProgramFiles" (x86)")`确实返回值`C:\ Program Files(x86)`,这当然很棒,因为听起来这样的变量不能被用户修改或删除; 那是这样吗?`ProgramFiles(x86)`某种"内部"环境变量? (2认同)

Jam*_*uis 54

请注意,os.arch酒店仅提供JRE的架构,而不是底层的操作系统.

如果在64位系统上安装32位jre,System.getProperty("os.arch")将返回x86

为了实际确定底层架构,您需要编写一些本机代码.有关详细信息,请参阅此帖子(以及示例本机代码的链接)


Cru*_*yro 5

我使用命令提示符(命令 - > wmic OS获取OSArchitecture)来获取操作系统体系结构.以下程序有助于获取所有必需参数:

import java.io.*;

public class User {
    public static void main(String[] args) throws Exception {

        System.out.println("OS --> "+System.getProperty("os.name"));   //OS Name such as Windows/Linux

        System.out.println("JRE Architecture --> "+System.getProperty("sun.arch.data.model")+" bit.");       // JRE architecture i.e 64 bit or 32 bit JRE

        ProcessBuilder builder = new ProcessBuilder(
            "cmd.exe", "/c","wmic OS get OSArchitecture");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        String result = getStringFromInputStream(p.getInputStream());

        if(result.contains("64"))
            System.out.println("OS Architecture --> is 64 bit");  //The OS Architecture
        else
            System.out.println("OS Architecture --> is 32 bit");

        }


    private static String getStringFromInputStream(InputStream is) {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {

            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();

    }

}
Run Code Online (Sandbox Code Playgroud)