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

本文介绍如何利用Java Native Access (JNA) 在Java中获取和设置Windows操作系统的文件创建时间、修改时间和访问时间,避免了使用JNI或C/C++编写DLL。示例代码展示了如何调用Win32 API的GetFileTime和SetFileTime等函数。
摘要由CSDN通过智能技术生成

最近有个项目,需要把文件从 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 操作系统文件时间&#

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值