最近有个项目,需要把文件从 Web 服务器上下载下来,并根据 Web 服务器返回的文件时间设置为本地文件的“创建时间”(有点像 FlashGet 1.73 General 选项中的“Get File Date And Time From Server”一样)。
java.io.File 里提供的只有设置文件的“最后修改时间”,而文件的“创建时间”是 Windows 操作系统特有的东西,网上对此问题的答案基本都是用 C/C++ 自己写一个 DLL,然后通过 JNI - Java Native Interface 调用之。方法就是这样,只是有没有一种纯 Java 的解决方法?
依旧依赖 Google 的搜索,找到了 JNA - Java Native Access (http://jna.dev.java.net)。JNA 官方网站的解释:
JNA provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code—no JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes. Access is dynamic at runtime without code generation.
JNA allows you to call directly into native functions using natural Java method invocation. The Java call looks just like it does in native code. Most calls require no special handling or configuration; no boilerplate or generated code is required.
The JNA library uses a small native library stub to dynamically invoke native code. The developer uses a Java interface to describe functions and structures in the target native library. This makes it quite easy to take advantage of native platform features without incurring the high overhead of configuring and building JNI code for multiple platforms.
While some attention is paid to performance, correctness and ease of use take priority.
JNA includes a platform library with many native functions already mapped as well as a set of utility interfaces that simplify native access.
虽然 JNA 目前仍处于“孵化阶段”(3.2.7),但对于目前的需求已经足够用了。下面的示例代码涉及到 Win32 API 的 6 个函数:
- GetFileTime
- SetFileTime
- CreateFile
- CloseHandle
- GetLastError
- FormatMessage
JNA 获取/设置 Windows 操作系统文件时间&#