Java 通过 JNA (Java Native Access) 获取、设置 Windows 操作系统的文件创建时间、文件修改时间、文件访问时间

来源:互联网 发布:网络进货渠道有哪些 编辑:程序博客网 时间:2024/05/16 07:30

最近有个项目,需要把文件从 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 操作系统文件时间(创建时间、最后修改时间、最后访问时间)的示例代码:

 

测试输出:

D:/Software/Development/java.net/jna - Java Native Access>java -cp .;..;jna.jar;platform.jar WindowsFileTime c:/pagefile.sys c:/AUTOEXEC.BAT文件 c:/pagefile.sys        打开文件失败,错误码:32 另一个程序正在使用此文件,进程无法访问。文件 c:/AUTOEXEC.BAT        创建时间:2007-03-01 10:58:19.749        修改时间:2007-03-01 10:58:19.749        访问时间:2010-07-23 10:04:05.546D:/Software/Development/java.net/jna - Java Native Access>java -cp .;..;jna.jar;platform.jar WindowsFileTime Advapi32Dll.java文件 Advapi32Dll.java        创建时间:2010-07-23 11:11:34.484        修改时间:2010-07-23 00:00:00.0        访问时间:2010-07-23 17:33:22.031SetFileTime (最后修改时间) 成功

 

 

相关资源:

  • JNA 主页: http://jna.dev.java.net
  • JNA 下载: http://jna.dev.java.net/servlets/ProjectDocumentList
原创粉丝点击