java.nio.file.Files.isWritable方法用于测试一个文件是否可写。但是对于文件夹,这个办法并不能用来测试文件夹是否可以创建子文件夹或文件。 比如对于匿名(只读)访问一个网络共享文件夹,isWritable返回是true
Path path3=Paths.get("\\\\SERVER\\share");//匿名用户只有读取权限的共享文件夹 System.out.println(Files.isWritable(path3));//返回true
所以如果想判断一个文件夹是不是真的可写,这个办法是不靠谱的。怎么办呢?看来只有去尝试创建文件和文件夹才能真判断文件夹是否可写了,于是想到了用于创建临时文件夹和临时文件的两个方法Files.createTempDirectory,Files.createTempFile
,用这两个方法尝试创建临时文件夹和临时文件,如果成功并且能删除就说明该文件夹可以可写。
代码很简单:
/** * 判断一个文件夹是否可创建文件/文件夹及可删除 * @param dir * @return */ public static boolean isWritableDirectory(Path dir) { if (null == dir) throw new IllegalArgumentException("the argument 'dir' must not be null"); if (!Files.isDirectory(dir)) throw new IllegalArgumentException("the argument 'dir' must be a exist directory"); try { Path tmpDir = Files.createTempDirectory(dir, null); Files.delete(tmpDir); } catch (IOException e) { return false; } try { Path tmpFile = Files.createTempFile(dir, null, null); Files.delete(tmpFile); } catch (IOException e) { return false; } return true; }
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句