Prevent file deletion, but allow to copy

84 Views Asked by At

I need to lock a file using Java to prevent file deletion by another process, but allow copying of this file. It should be made by two methods like lock() and unlock().

I tried using a FileLock, but it also denies copying. Аre there any other ways to lock a file?

How is it works now:

        public static void main(String[] args) {
    
            ArrayList<File> files = new ArrayList<>();
            files.add(new File("C:\\Work\\Test\\a.txt"));
            files.add(new File("C:\\Work\\Test\\b.txt"));
            files.add(new File("C:\\Work\\Test\\c.txt"));


            HashMap<String,FileLock> locks = lockFile(files);
            StaticHelper.awaiter(15000); // just idle for manual checking
            locks.entrySet().forEach(x->{
                unlockFile(x.getValue());
                System.out.println(x.getKey() + " unlocked");
                StaticHelper.awaiter(5000);
        });

        private static HashMap<String,FileLock> lockFile(ArrayList<File> files){
            HashMap<String,FileLock> locks = new HashMap<>();
            for (int i=0; i<files.size(); i++) {

                try {
                    FileChannel channel = new RandomAccessFile(files.get(i), "rw").getChannel();
                    FileLock lock = channel.lock();
                    locks.put(files.get(i).getName(), lock);
                    System.out.println(files.get(i).getName() + " locked");
    
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return null;
                }
            }
            return locks;
    
        }
    
        private static void unlockFile(FileLock lock) {
            try {
                if( lock != null ) {
                        lock.release();
                        lock.channel().close();
                    }
                System.out.println("Unlocked");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
1

There are 1 best solutions below

1
Mr_Thorynque On

You can find documentation about that you can use a shared lock, other process can read the file.

    try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ);
        FileLock lock = channel.lock(0, Long.MAX_VALUE, true)) {
        // read from the channel
    }