问题
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.
To avoid multiple threads reading same files, in my ItemReader I take a FileLock and avoid other threads to read from it.
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.
Question is, can I move the file from inbox to archive without giving up the FileLock?
回答1:
Try to copy the file using 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();
}
}
Good luck
来源:https://stackoverflow.com/questions/35093757/move-a-file-without-releasing-lock