There is xml, which I open for editing on java.

How to make so that at the time of work tulza, no one else could edit the file?

Addition: It is necessary to take into account that the tool may be terminated abnormally, therefore file.setWritable(false) probably not work (the file will remain locked)

Unfortunately, the option

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

It does not work, because if, while the program is running, it is abnormally terminated, the file remains read only.

  • If you are given an exhaustive answer, mark it as correct (tick the selected answer). - andreycha
  • How is it abnormal? Is someone interrupting him or is he falling for lack of memory? - Artem Konovalov

2 answers 2

setWritable is 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); })); 
  • Could you give a hint 1. what should be instead of the arrow in the new thread (() -> {2. record should be called from a static method or maybe from a normal one? - Roberto
  • 2
    This is called lamba function, try it, you will like it. If you are writing to java version 1.7 and below, you can write like this: new Thread (new Runnable () {@Override public void run () {file.setWritable (true);}}); - Artem Konovalov
 public class JavaApplication17 { /** * @param args the command line arguments */ public static void main(String[] args) { final File file = new File("myFile"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { file.setWritable(true); } }); try { file.setWritable(false); Thread.sleep(1000000); } catch (Exception e) { // обработка исключений } finally { file.setWritable(true); } } 
  • This option works. - DimXenon
  • Alas, not always the code that works is correct and correct. - Artem Konovalov
  • Describe what the example is incorrect and incorrect, please. In order not to repeat mistakes. - DimXenon
  • OK. mainThread.join () why? This is absolutely useless design, because The main thread has already died after shutdownhooks start running. Plus the catch sheet from the catch is not beautiful, especially since they have the same thing - Artem Konovalov
  • About bed sheets - let's say. Cosmetics. mainThread.join () - in this case is not needed. (As the output of the absolute path and writing to the file is optional.) - DimXenon