2

我试图在解组之前锁定文件并在编组后释放。

public T lockedReadingFromFile(String filePath, Class<T> clas) {
    T object = null;
    JAXBContext context = null;
    Unmarshaller unMarshaller = null;
    try {
        fileToBlock = new File(filePath);
        file = new RandomAccessFile(fileToBlock, "rw");
        FileChannel fileChannel = file.getChannel();
        fileLock = fileChannel.tryLock();
        if (fileLock != null) {
            System.out.println("File is locked");
        }
        context = JAXBContext.newInstance(clas);
        unMarshaller = context.createUnmarshaller();
        object = (T) unMarshaller.unmarshal(fileToBlock);

    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return object;
}

但是代码在行内解组期间抛出异常object = (T) unMarshaller.unmarshal(fileToBlock);

File is locked
javax.xml.bind.UnmarshalException
 - with linked exception:
[java.io.IOException: The process cannot access the file because another process has locked a portion of the file]

为什么会这样?

4

1 回答 1

1
unMarshaller.unmarshal(fileToBlock)

在这里,unmarshaller 提供了java.io.File参数,因此它尝试通过自己创建新的输入流来读取文件。

相反,FileInputStream使用JAXB.

   FileInputStream fileToBlockStream = new FileInputStream(fileToBlock);
   FileChannel fileChannel = fileToBlockStream.getChannel();
   fileLock = fileChannel.tryLock();

   unMarshaller = context.createUnmarshaller();
   object = (T) unMarshaller.unmarshal(fileToBlockStream);
于 2014-08-22T12:40:30.623 回答