进程无法访问文件,因为使用java.nio.channels.FileLock时另一个进程已锁定了一部分

时间:2019-10-24 18:28:38

标签: java file nio file-locking filelock

当我在Windows中运行以下代码部分时(在Linux中,我不会出现此类错误),标题中将出现java.io.IOException。我该如何解决这个问题?谢谢

    RandomAccessFile randomAccessFile = null;
    try {
        randomAccessFile = new RandomAccessFile(fileToAccess, "rw");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    FileChannel outChannel = randomAccessFile.getChannel();


    try (outChannel; FileLock fileLock = outChannel.lock()) {

        FileManagement fileManagement = new FileManagement();

         Path path = Paths.get(fileToAccess);
         List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

        fileLock.release();

    } catch (OverlappingFileLockException | IOException ex) {
        System.err.println("Exception occured while trying to get a lock on File... " + ex.getMessage());
        System.exit(-1);
    }

0 个答案:

没有答案