且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法在Windows中使用Java删除文件

更新时间:2023-12-03 20:00:52

我最近遇到了这个问题.我创建了一种变通方法,其中如果file.delete()返回false,则检查file.exists()返回true,如果是,我稍等一下,然后重试,并在尝试多次后放弃.

I ran into this recently. I created a workaround where if file.delete() returns false I check if file.exists() returns true and if so, I wait a bit then try again and give up after some number of tries.

我未经证实的怀疑是Windows上的病毒检查器锁定了文件以检查文件,并等待病毒检查器完成.

My unproven suspicion is that virus checkers on Windows lock the file to examine the file and waiting allows the virus checker to finish.

            // Remove the original file.
            if(!file.delete()) {
                // wait a bit then retry on Windows
                if (file.exists())
                {
                    for (int i = 0; i < 6; i++)
                    {
                        Thread.sleep(500);
                        System.gc();
                        if (file.delete())
                           break;
                    }