Java - How to Lock Files Using File Channel (Java I/O Part 1)

in #utopian-io7 years ago (edited)

c82-java-fund-logo.jpg
Source: https://academy.oracle.com/en/oa-assets/i/c82/c82-java-fund-logo.jpg

What Will I Learn?

In this tutorial, I will guide you how to lock files by using File Channel while other processes will be blocked from attempting to gain access to the same file until the current process releases the lock. But, before we go any further, we need to grasp the fundamentals of reading from or writing to the stream based on the Java™ platform. A stream can represent many different kinds of sources and targets, including files, devices, memory or others.

  • Java™ I/O Stream
  • Java™ File Channel

Requirements


Difficulty

  • Basic

Tutorial Contents



  • File Channel

    And finally the time has come for us to implement file locking using File Channel. And here's the source codes.

       
       import java.io.BufferedReader;
       import java.io.IOException;
       import java.io.InputStreamReader;
       import java.io.RandomAccessFile;
       import java.nio.ByteBuffer;
       import java.nio.channels.FileChannel;
       import java.nio.channels.FileLock;
       import java.util.List;
       
    public class Main { public static void main(String[] args) { try(RandomAccessFile r = new RandomAccessFile("D:/Lock.txt", "rw"); FileChannel fc = r.getChannel()) { /** * Lock file */ FileLock lock = fc.tryLock(); System.out.println("Locking file was successful"); System.out.println("Enter lines (to stop, type: \"stop\"):"); String line; List lines = new java.util.ArrayList<>(); try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { while(!(line = reader.readLine()).equals("stop")) lines.add(line); } int i = 0, n; ByteBuffer buffer; buffer = ByteBuffer.wrap(lines.get(i).getBytes()); fc.write(buffer); for(n = lines.size(); ++i < n; ) { buffer = ByteBuffer.wrap((System.lineSeparator() + lines.get(i)).getBytes()); fc.write(buffer); } /** * You do not have to declare this, * because we already use try-with-resources which will close `lock` automatically. */ //lock.release(); } catch(IOException e) { e.printStackTrace(); } } }

    Testing

    We'll try a simple test by creating a new file, i.e.: D:/Lock.txt and the whole contents come from the Console stream. The file will remain locked until the user has finished modifying the file.

    Untitled 012.png

    While we're typing and not trying to interrupt by giving the stop word, the file:D:/Lock.txt will not be able to be changed by anyone. And you will get a message like in the picture below (running on Windows platform).

    Untitled 013.png

    Then when you release the lock (of course, by giving the input stop), then another process that is accessing the same file has been able to change the contents of the file.
    Congratulations! We have successfully locked the file by using File Channel.


Thank you!

Share with heart



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

I can learn a lot from your posts. Good job!

Thank you.
Keep following my posts.

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @murez-nst I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.20
TRX 0.25
JST 0.039
BTC 97371.04
ETH 3473.35
USDT 1.00
SBD 3.20