简体   繁体   中英

Creating a Java program that locks a file

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.

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");

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM