arsen_adzhiametov
arsen_adzhiametov

Reputation: 696

JAXB and File Locking

I'm trying to lock file before unmarshalling and release after marshalling.

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;
}

But code throws exception during unmarshalling in line 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]

Why is this happening?

Upvotes: 2

Views: 1195

Answers (1)

ulab
ulab

Reputation: 1089

unMarshaller.unmarshal(fileToBlock)

Here, unmarshaller is provided with the java.io.File argument, so it tries to read the file by creating new inputstream on its own.

Instead, use FileInputStream to read the XML using JAXB.

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

   unMarshaller = context.createUnmarshaller();
   object = (T) unMarshaller.unmarshal(fileToBlockStream);

Upvotes: 1

Related Questions