4

Java 是否有可以调用的 API 可以知道进程或 .exe 文件是 32 位还是 64 位?- 不是运行代码的 JVM

4

3 回答 3

11

没有用于确定外部进程是 32 位还是 64 位的标准 Java API。

如果你想这样做,你要么需要使用本机代码,要么调用外部实用程序来执行此操作。在这两种情况下,解决方案都可能是特定于平台的。以下是一些可能的(特定于平台的)线索:

(注意,在 Windows 的情况下,解决方案是测试“.exe”文件而不是正在运行的进程,因此您需要先能够确定相关的“.exe”文件...)

于 2013-08-06T00:30:28.403 回答
2

我在 Java 中为 Windows 编写了一个方法,它查看相同的标题,dumpbin而不必在系统上安装它(基于这个答案)。

/** 
 * Reads the .exe file to find headers that tell us if the file is 32 or 64 bit.
 * 
 * Note: Assumes byte pattern 0x50, 0x45, 0x00, 0x00 just before the byte that tells us the architecture.
 * 
 * @param filepath fully qualified .exe file path.
 * @return true if the file is a 64-bit executable; false otherwise.
 * @throws IOException if there is a problem reading the file or the file does not end in .exe.
 */
public static boolean isExeFile64Bit(String filepath) throws IOException {
    if (!filepath.endsWith(".exe")) {
        throw new IOException("Not a Windows .exe file.");
    }

    byte[] fileData = new byte[1024]; // Should be enough bytes to make it to the necessary header.
    try (FileInputStream input = new FileInputStream(filepath)) {
        int bytesRead = input.read(fileData);
        for (int i = 0; i < bytesRead; i++) {
            if (fileData[i] == 0x50 && (i+5 < bytesRead)) {
                if (fileData[i+1] == 0x45 && fileData[i+2] == 0 && fileData[i+3] == 0) {
                    return fileData[i+4] == 0x64;
                }
            }
        }
    }

    return false;
}

public static void main(String[] args) throws IOException {
    String[] files = new String[] {
            "C:/Windows/system32/cmd.exe",                           // 64-bit
            "C:/Windows/syswow64/cmd.exe",                           // 32-bit
            "C:/Program Files (x86)/Java/jre1.8.0_73/bin/java.exe",  // 32-bit
            "C:/Program Files/Java/jre1.8.0_73/bin/java.exe",        // 64-bit
            };
    for (String file : files) {
        System.out.println((isExeFile64Bit(file) ? "64" : "32") + "-bit file: " + file + ".");
    }
}

主要方法输出以下内容:

64-bit file: C:/Windows/system32/cmd.exe. 
32-bit file: C:/Windows/syswow64/cmd.exe. 
32-bit file: C:/Program Files (x86)/Java/jre1.8.0_73/bin/java.exe. 
64-bit file: C:/Program Files/Java/jre1.8.0_73/bin/java.exe.
于 2016-02-15T20:11:38.907 回答
1

Java 不附带任何标准 API,可让您确定程序是 32 位还是 64 位。

但是,在 Windows 上,您可以使用(假设您安装了平台 SDK)dumpbin /headers。调用它会产生有关文件的各种信息,其中包括有关文件是 32 位还是 64 位的信息。在输出中,在64-bit上,你会喜欢

8664 machine (x64)

32-bit上,你会得到类似的东西

14C machine (x86)

您可以在 SuperUser或Windows HPC 团队博客上阅读有关确定应用程序是否为 64 位的其他方法的更多信息。

于 2013-08-06T00:38:34.400 回答