Move a file without releasing lock

℡╲_俬逩灬. 提交于 2019-12-12 17:14:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!