2013-08-06 73 views

回答

11

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

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

(请注意,在在Windows的情况下,解决方案涉及到测试“.exe”文件而不是正在运行的进程,所以你需要能够首先确定相关的“.exe”文件...)

+0

谢谢Stephen! – Mango

+0

对于Windows,我总是查询系统环境变量“PROCESSOR_ARCHITECTURE”。如果它返回x86,那么您正在运行32位Windows。 – TheBlastOne

+0

@TheBlastOne - 但这是解决一个不同的问题......确定什么架构被用于这个过程。 –

1

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

但是,在Windows上,您可以使用(假设您已安装平台SDK)dumpbin /headers。调用这个函数将产生关于该文件的各种信息,关于该文件是32位还是64位的信息。在输出上64位,你会像

8664 machine (x64) 

32位,你会得到类似

14C machine (x86) 

你可以阅读更多有关其他方式determining if an application is 64-bit on SuperUserThe Windows HPC Team Blog

+0

感谢您的建议。我已经尝试过了,它在Visual Studio CMD中有效。 – Mango

1

我为Windows编写了一个Java的方法,它看起来像dumpbin相同的标题,而不必在系统上(基于this answer)。

/** 
* 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. 
相关问题