gpt4 book ai didi

java - 使用 Commons IO 复制时锁定文件

转载 作者:可可西里 更新时间:2023-11-01 13:51:15 25 4
gpt4 key购买 nike

我正在使用 Apache Commons IO:

     FileUtils.copyFileToDirectory(srcFile, destDir)

如何让 Windows 在复制过程中锁定目标文件?如果我使用 Windows 正确锁定文件:

      Runtime.getRuntime().exec(
"cmd /c copy /Y \"" + srcFile.getCanonicalPath() + "\" \""
+ destDir.getCanonicalPath() + "\"").waitFor();

注意事项:争用的不是本地程序,而是外部程序。正在将文件复制到远程系统。远程系统在完成复制之前正在处理文件。由于系统是Windows,普通拷贝会锁定文件并阻止外部程序访问。

最佳答案

java.nio.channels.FileChannel将使您获得 FileLock在文件上,使用底层文件系统的 native 方法,假设支持此类功能。

此锁跨机器上的进程运行,甚至是非 Java 进程。 (实际上,锁是代表特定的 JVM 实例持有的,因此不适合管理一个进程中的多个线程之间或同一 JVM 中的多个进程之间的争用)。

这里有很多注意事项,但如果您在 Windows 上工作,则值得研究一下。

来自javadoc:

This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.

Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified. The native file-locking facilities of some systems are merely advisory, meaning that programs must cooperatively observe a known locking protocol in order to guarantee data integrity. On other systems native file locks are mandatory, meaning that if one program locks a region of a file then other programs are actually prevented from accessing that region in a way that would violate the lock. On yet other systems, whether native file locks are advisory or mandatory is configurable on a per-file basis. To ensure consistent and correct behavior across platforms, it is strongly recommended that the locks provided by this API be used as if they were advisory locks.

On some systems, acquiring a mandatory lock on a region of a file prevents that region from being mapped into memory, and vice versa. Programs that combine locking and mapping should be prepared for this combination to fail.

On some systems, closing a channel releases all locks held by the Java virtual machine on the underlying file regardless of whether the locks were acquired via that channel or via another channel open on the same file. It is strongly recommended that, within a program, a unique channel be used to acquire all locks on any given file.

Some network filesystems permit file locking to be used with memory-mapped files only when the locked regions are page-aligned and a whole multiple of the underlying hardware's page size. Some network filesystems do not implement file locks on regions that extend past a certain position, often 230 or 231. In general, great care should be taken when locking files that reside on network filesystems.`

关于java - 使用 Commons IO 复制时锁定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/473379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com