jna 获取文件作者
时间: 2023-10-08 20:07:38 浏览: 45
JNA(Java Native Access)是一个Java库,可以让Java应用程序调用本地的C/C++动态链接库(DLL/SO)。如果要获取文件作者,需要使用Windows API中的GetFileVersionInfo函数和VerQueryValue函数。可以通过JNA调用这些函数来实现。
以下是示例代码:
```java
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Version;
public class FileVersionInfo {
public static void main(String[] args) {
String fileName = "C:\\Windows\\System32\\notepad.exe";
Version.VS_FIXEDFILEINFO fileInfo = getFileVersionInfo(fileName);
if (fileInfo != null) {
System.out.println("File version: " + fileInfo.dwFileVersionMS + "." + fileInfo.dwFileVersionLS);
System.out.println("Product version: " + fileInfo.dwProductVersionMS + "." + fileInfo.dwProductVersionLS);
String companyName = getStringFileInfo(fileName, "CompanyName");
System.out.println("Company name: " + companyName);
String fileDescription = getStringFileInfo(fileName, "FileDescription");
System.out.println("File description: " + fileDescription);
String fileVersion = getStringFileInfo(fileName, "FileVersion");
System.out.println("File version string: " + fileVersion);
String productName = getStringFileInfo(fileName, "ProductName");
System.out.println("Product name: " + productName);
String originalFilename = getStringFileInfo(fileName, "OriginalFilename");
System.out.println("Original filename: " + originalFilename);
String comments = getStringFileInfo(fileName, "Comments");
System.out.println("Comments: " + comments);
} else {
System.out.println("File version info not found.");
}
}
private static Version.VS_FIXEDFILEINFO getFileVersionInfo(String fileName) {
Version version = Version.INSTANCE;
int handle = version.GetFileVersionInfoSize(fileName, null);
if (handle <= 0) {
return null;
}
byte[] buffer = new byte[handle];
if (!version.GetFileVersionInfo(fileName, 0, handle, buffer)) {
return null;
}
Pointer pointer = new Pointer(0);
int[] length = new int[1];
if (!version.VerQueryValue(buffer, "\\", pointer, length)) {
return null;
}
return new Version.VS_FIXEDFILEINFO(pointer.getByteArray(0, length[0]));
}
private static String getStringFileInfo(String fileName, String key) {
Version version = Version.INSTANCE;
int handle = version.GetFileVersionInfoSize(fileName, null);
if (handle <= 0) {
return null;
}
byte[] buffer = new byte[handle];
if (!version.GetFileVersionInfo(fileName, 0, handle, buffer)) {
return null;
}
Pointer pointer = new Pointer(0);
int[] length = new int[1];
if (!version.VerQueryValue(buffer, "\\StringFileInfo\\040904b0\\" + key, pointer, length)) {
return null;
}
return pointer.getString(0);
}
}
```
其中,`getFileVersionInfo`函数获取文件的版本信息,`getStringFileInfo`函数获取指定键的字符串信息。在`getStringFileInfo`函数中,`040904b0`是代表英语(美国)的语言和地区代码,可以根据需要修改。
注意,该代码只适用于Windows操作系统。如果要在其他操作系统上运行,需要使用不同的API函数。