Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Java program that locks a file

Tags:

java

How do I lock a file so that a user can only unlock it using my Java program?

import java.nio.channels.*;
import java.io.*;

public class filelock {

  public static void main(String[] args) {

    FileLock lock = null;
    FileChannel fchannel = null;

    try {
      File file = new File("c:\\Users\\green\\Desktop\\lock.txt");

      fchannel = new RandomAccessFile(file, "rw").getChannel();

      lock = fchannel.lock();
    } catch (Exception e) {
    }
  }
}

This is my sample code. It doesn't give me what I want. I want it to deny one access to read or to write the file, until I use my Java program to unlock it.

like image 655
Green Onyeji Avatar asked Jul 06 '13 18:07

Green Onyeji


2 Answers

You can do this where you want to lock:

File f1 = new File(Your file path);
f1.setExecutable(false);
f1.setWritable(false);
f1.setReadable(false);

And for unlock you can just do this:

File f1 = new File(Your file path);
f1.setExecutable(true);
f1.setWritable(true);
f1.setReadable(true);

Before applying

Check if the file permission allow:

file.canExecute(); – return true, file is executable; false is not.
file.canWrite(); – return true, file is writable; false is not.
file.canRead(); – return true, file is readable; false is not.

For a Unix system you have to put in this code:

Runtime.getRuntime().exec("chmod 777 file");
like image 194
TheLittleNaruto Avatar answered Oct 01 '22 11:10

TheLittleNaruto


You can lock the file by using Java code in a very simple way like:

Process p = Runtime.getRuntime().exec("chmod 755 " + yourfile);

Here exec is a function which accepts a string value. You can put any command in that it will execute.

Or you can do it with another way like:

File f = new File("Your file name");
f.setExecutable(false);
f.setWritable(false);
f.setReadable(false);

To be sure, check the file:

System.out.println("Is Execute allow: " + f.canExecute());
System.out.println("Is Write allow: " + f.canWrite());
System.out.println("Is Read allow: " + f.canRead());
like image 34
Simmant Avatar answered Oct 01 '22 11:10

Simmant