Java 中强制删除文件的方法
在系统开发时,有时需要在程序中把正在用到plugin文件删除,重新更新。这需要首先在java程序中停止使用这个plugin文件,然后删除,重新更新。我在开发是遇到这样的问题,在java中停止使用了plugin文件,但是在用过FileObj.delete时,返回false,在文件系统中删除plugin文件时,OS报错,说该文件正在使用中,等几秒中在删除就可以删除了。
我猜想可能是java已经不用该plugin文件了,但是OS还认为该文件还在被使用,所以报错,所以就写了个方法来强制删除改文件,不知道这样写有没有什么不妥?欢迎来拍砖!
/** * try to delete given file , try 10 times * @param f * @return true if file deleted success, nor false; */public static boolean forceDelete(File f){ boolean result = false; int tryCount = 0; while(!result && tryCount++ <10) {logger.debug("try to delete file "+ f.getName() +" cnt:"+tryCount);System.gc();result = f.delete(); } return result;}/** * Delete a file. If file is a directory, delete it and all sub-directories. * <p> * The difference between File.delete() and this method are: * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>You get exceptions when a file or directory cannot be deleted. * (java.io.File methods returns a boolean)</li> * </ul> * * @param file file or directory to delete, must not be <code>null</code> * @throws NullPointerException if the directory is <code>null</code> * @throws IOException in case deletion is unsuccessful */ public static void forceDelete(File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { if (!file.exists()) { throw new FileNotFoundException("File does not exist: " + file); } if (!file.delete()) { String message = "Unable to delete file: " + file; throw new IOException(message); } } }/** * Delete a file. If file is a directory, delete it and all sub-directories. * <p> * The difference between File.delete() and this method are: * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>You get exceptions when a file or directory cannot be deleted. * (java.io.File methods returns a boolean)</li> * </ul> * * @param file file or directory to delete, must not be <code>null</code> * @throws NullPointerException if the directory is <code>null</code> * @throws IOException in case deletion is unsuccessful */ public static void forceDelete(File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { if (!file.exists()) { throw new FileNotFoundException("File does not exist: " + file); } if (!file.delete()) { String message = "Unable to delete file: " + file; throw new IOException(message); } } }收下啊 4 楼 jwmianzu 2007-08-21 楼主,System.gc()调用以后不适立刻就进行垃圾回收的,如果不是对跨平台要求严格看是否能用java调用系统的强行删除命令。别的办法我也不知道了 5 楼 coolzyt 2007-08-21 这样10次太快了吧,可能还是删不掉,建议再加一个Thread.sleep(1000)? 6 楼 IvanLi 2007-08-22 我尝试过多次,一般情况下cnt=1时就能删除,现在cnt最大只是到5就结束了 7 楼 抛出异常的爱 2007-08-22 Ivan Li 写道我尝试过多次,一般情况下cnt=1时就能删除,现在cnt最大只是到5就结束了