Lock and delete files

I am making a program in java that monitors and backs up a directory. From time to time I have to upload modified files to the repository or upload if there is a new version. To do this, I need to lock the file so that the user cannot modify the contents or delete it. I am currently using this code to lock a file:

        file = new RandomAccessFile("C:\\Temp\\report.txt", "rw");

        FileChannel fileChannel = file.getChannel();
        fileLock = fileChannel.tryLock();
        if (fileLock != null) {
            System.out.println("File is locked");

            try{

            //Do what i need    

            }catch (Exception e){//Catch exception if any
                System.err.println("Error: " + e.getMessage());
            }
        }
        else{
            System.out.println("Failed");
        }
    } catch (FileNotFoundException e) {
        System.out.println("Failed");
    }finally{
        if (fileLock != null){
            fileLock.release();
        }

However, if there is a new version, I need to delete the old file and replace it with the new one. But locking the file does not allow me to delete the file.

Should I unlock and delete it for writing, believing that the user will not write to the file? Or is there any other way to do this?

+5
source share
1 answer

You can trim the file:

fileChannel.truncate(0);

, , .

:

, , . . , , .

http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#truncate%28long%29

+3

All Articles