小编Arc*_*ana的帖子

在已锁定的文件上打开文件输出流会覆盖它

我遇到了这种情况,却不明白为什么会这样。有人可以帮我理解nio文件锁定的行为。

我使用FileOutputStream打开了一个文件,并使用nio FileLock获得了排他锁之后,我将一些数据写入了文件中。没有释放锁。试图在同一文件上打开另一个FileOutputStream以获取锁并执行写操作,并期望此操作会失败。但是打开第二个fileoutputstream会覆盖已经写入数据的已经锁定的文件,甚至在我尝试获得第二个锁之前。这是预期的吗?我的理解是获得排他锁将防止对锁定文件进行任何更改。尝试获取另一个锁定时,如何防止覆盖文件?(就好像另一个进程试图在另一个vm上的同一文件上获得锁一样?)

我尝试过的示例程序:

        File fileToWrite = new File("C:\\temp\\myfile.txt");
        FileOutputStream fos1 = new FileOutputStream(fileToWrite);
        FileOutputStream fos2 =null;
        FileLock lock1,lock2 =null;
        lock1=fos1.getChannel().tryLock();
        if(lock1!=null){
            //wrote date to myfile.txt after acquiring lock
            fos1.write(data.getBytes());
            //opened myfile.txt again and this replaced the file
            fos2 = new FileOutputStream(fileToWrite);
            //got an overlappingfilelock exception here
            lock2=fos2.getChannel().tryLock();
            fos2.write(newdata.getBytes());
            }

        lock1.release();
        fos1.close();
        if(lock2!=null)
            lock2.release();
        fos2.close();
Run Code Online (Sandbox Code Playgroud)

还尝试将以上内容分成两个程序。从1st开始执行,并在1st等待时开始执行。被program1锁定的文件被program2覆盖。示例如下:

程序1:

    File fileToWrite = new File("C:\\temp\\myfile.txt");
    FileOutputStream fos1 = new FileOutputStream(fileToWrite);
    FileLock lock1 =null;
    lock1=fos1.getChannel().tryLock();
    if(lock1!=null){
        //wrote date to myfile.txt after acquiring lock
        fos1.write(data.getBytes()); …
Run Code Online (Sandbox Code Playgroud)

java concurrency filelock

5
推荐指数
1
解决办法
2792
查看次数

标签 统计

concurrency ×1

filelock ×1

java ×1