title: Prevent deleting lock file using nio
body: <p>We want to prevent other processes from deleting the temp directory of our running application. That way we create a temp directory and a <em>lock</em> file in it. The only way I found at that prevents deleting this file is by using <code>RandomAccessFile</code>:</p>
  <pre><code>tempDirectory = Files.createTempDirectory(&quot;myapp&quot;);
  final Path lockFile = Files.createTempFile(tempDirectory, &quot;lock&quot;, null);
  randomAccessFile = new RandomAccessFile(lockFile.toFile(), &quot;rw&quot;);
  </code></pre>
  <p><strong>Is there a way to achieve the same with nio?</strong> I have tried with the following code:</p>
  <pre><code>import java.io.*;
  import java.nio.channels.*;
  import java.nio.file.*;
  
  public class CreateLock {
  
      public static void main(String[] args) throws IOException, InterruptedException {
          final Path path = Paths.get(&quot;C:/temp/test&quot;);
          Files.createFile(path);
          final FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE);
          channel.lock();
  
          for (int i = 60; i-- &gt; 0; ) {
              System.out.println(i);
              if (!Files.isRegularFile(path)) {
                  System.out.println(&quot;File is gone&quot;);
                  break;
              }
  
              Thread.sleep(10_000);
          }
  
          channel.close();
      }
  }
  </code></pre>
  <p>but a second Java application with this code</p>
  <pre><code>import java.io.*;
  import java.nio.file.*;
  
  public class DeleteLock {
  
      public static void main(String[] args) throws IOException {
          final Path path = Paths.get(&quot;C:/temp/test&quot;);
          Files.delete(path);
      }
  }
  </code></pre>
  <p>can delete the file.</p>