问题描述
我在Spring Batch应用程序中使用Java NIO.该应用程序查找目录(例如/shared/inbox),其中/shared是在不同JVM上运行的所有应用程序实例之间的网络共享磁盘.
I am using Java NIO in spring batch application. The application looks in a directory (e.g. /shared/inbox) where /shared is network shared disk among all instances of applications running on different JVMs.
为避免多个线程读取相同的文件,请在ItemReader中使用FileLock,并避免其他线程从中读取文件.
To avoid multiple threads reading same files, in my ItemReader I take a FileLock and avoid other threads to read from it.
阅读完毕后,我想将文件移到另一个目录(例如/shared/archive).但是,除非我放弃FileLocl,否则Files.move方法无法做到这一点,并且如果我放弃锁,则冒着其他线程选择该文件的风险.
While I am done reading, I want to move the file to another directory (e.g. /shared/archive). But the Files.move method cannot do that unless I give up the FileLocl, and if I give up the lock, I run the risk of some other thread picking the file.
问题是,我可以在不放弃FileLock的情况下将文件从收件箱移至存档吗?
Question is, can I move the file from inbox to archive without giving up the FileLock?
推荐答案
尝试使用java.nio.channels.FileChannel
private static void copyFileUsingFileChannels(File source, File dest)throws IOException {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
inputChannel.close();
outputChannel.close();
}
}
祝你好运
这篇关于移动文件而不释放锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!