java 文件锁定和删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11179776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:05:32  来源:igfitidea点击:

File locking and delete

javafilelockingdelete-file

提问by user1308768

I'm making a program in java that monitors and backup a directory. From time to time I have to upload modified files to the repository or download if there is a new version of it. In order to do this I have to lock the file so that the user is unable to change the contents or delete it. Currently I'm using this code to lock the file:

我正在用 java 制作一个程序来监视和备份目录。有时我必须将修改后的文件上传到存储库或下载它的新版本。为了做到这一点,我必须锁定文件,以便用户无法更改内容或删除它。目前我正在使用此代码来锁定文件:

        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 have to delete the old file and replace with new one. But File lock does not allow me to delete the file.

但是,如果有新版本,我必须删除旧文件并替换为新文件。但是文件锁定不允许我删除文件。

Should I unlock and delete it write away, trusting that the user wont write in file? Or is there any other way of doing this?

我应该解锁并删除它,相信用户不会写入文件吗?或者有没有其他方法可以做到这一点?

采纳答案by Francisco Spaeth

You could truncate the file:

您可以截断文件:

fileChannel.truncate(0);

and afterwards write the new version over it, this wouldn't create the time gap in which the user can create the file again.

然后在上面写新版本,这不会造成用户可以再次创建文件的时间间隔。

From documentation:

从文档:

If the given size is less than the file's current size then the file is truncated, discarding any bytes beyond the new end of the file. If the given size is greater than or equal to the file's current size then the file is not modified. In either case, if this channel's file position is greater than the given size then it is set to that size.

如果给定的大小小于文件的当前大小,则文件将被截断,丢弃超出文件新末尾的任何字节。如果给定的大小大于或等于文件的当前大小,则不会修改文件。在任一情况下,如果此通道的文件位置大于给定大小,则将其设置为该大小。

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

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