Creating a Java program that locks a file

How to lock a file so that the 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 does not give me what I want. I want him to refuse one read or write access to the file until I use my Java program to unlock it.

+8
java
source share
2 answers

You can do this if you want to block:

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

And to unlock, you can simply do this:

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

Before use

Check if file permission is allowed:

 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 must enter this code:

 Runtime.getRuntime().exec("chmod 777 file"); 
+15
source share

You can lock the file using Java code in a very simple way, for example:

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

Here exec is a function that takes a string value. You can put any command in its execution.

Or you can do it in another way, for example:

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

To verify, 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()); 
+2
source share

All Articles