# How to lock a file before writing in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 7, 2019. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-lock-file-before-writing

> A short tutorial to learn how to lock a file before writing in Java.

In Java, you can use the `RandomAccessFile` class in combination with `FileChannel` to lock a file before writing.

Here is  an example that uses `FileLock` from [NIO API](https://attacomsian.com/blog/java-read-write-files-nio-api) (classes in `java.nio.*` package) to lock a file before writing data and then release the lock once write operation is completed:

```java
try {
    // open file in read-write mode
    RandomAccessFile writer = new RandomAccessFile("output.txt", "rw");

    // lock file
    FileLock lock = writer.getChannel().lock();

    // wait 5s (demo purpose only)
    TimeUnit.SECONDS.sleep(5);

    // write to file
    writer.write("Hey, there!".getBytes());

    // release lock
    lock.release();

    // close the file
    writer.close();

} catch (IOException | InterruptedException ex) {
    ex.printStackTrace();
}
```

Now try to access the file, while it is locked, in another process:

```java
try {
    // read all lines
    List<String> lines = Files.readAllLines(Paths.get("output.txt"));

    // print all lines
    lines.forEach(System.out::println);

} catch (IOException ex) {
    ex.printStackTrace();
}
```

You should see the following exception printed on the console:

```bash
java.io.IOException: The process cannot access the file because another process has locked a portion of the file
    at java.base/sun.nio.ch.FileDispatcherImpl.read0(Native Method)
    at java.base/sun.nio.ch.FileDispatcherImpl.read(FileDispatcherImpl.java:54)
    at java.base/sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:276)
    at java.base/sun.nio.ch.IOUtil.read(IOUtil.java:245)
    ...
```

## Further Reading

You may be interested in other Java I/O articles:

* [Reading and Writing Files in Java](https://attacomsian.com/blog/java-read-write-files)
* [How to Read and Write Text Files in Java](https://attacomsian.com/blog/java-read-write-text-files)
* [How to Read and Write Binary Files in Java](https://attacomsian.com/blog/java-read-write-binary-files)
* [Reading and Writing Files using Java NIO API](https://attacomsian.com/blog/java-read-write-files-nio-api)
* [How to read a file line by line in Java](https://attacomsian.com/blog/how-to-read-a-file-line-by-line-in-java)
