how to lock xml for the duration of the tool in JAVA

Question:

There is an xml that I open for editing in java.

How to make sure that no one else can edit the file while the tool is running?

Addendum: Be aware that the tool can crash, so file.setWritable(false) probably won't work (the file will remain locked)

Unfortunately the option

 Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    file.setWritable(true);
}));

Not suitable, because if, while the program is running, it crashes, the file remains read only.

Answer:

setWritable are quite suitable for your purposes. And so that the file does not remain locked after the application is stopped, this can help

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        file.setWritable(true);
    }));
Scroll to Top