九月 19, 2023
·
编程基础
Java创建文件或者目录后修改权限对其他用户可读可写
在Java中有时候会碰到一种情况,就是创建出来的目录或者文件,需要对别的用户也可读可写,这时候就需要修改创建的文件的权限,一般来说可以有不同的做法。
一种是直接在file本身上修改:
file.setWritable(true, false) file.setReadable(true, false)
|
或者也可以自己实现,去控制不同的权限:
public static void changePermission(File file) { Set<PosixFilePermission> perms = new HashSet<>(); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_READ); try { Files.setPosixFilePermissions(file.toPath(), perms); } catch (IOException e) { throw new UncheckedIOException(e); } }
|
写个测试:
@Test public void testChangePermission() throws IOException { String basePath = System.getProperty("java.io.tmpdir", "/tmp"); String pattern = basePath.endsWith("/") ? "%s%s" : "%s/%s"; String testDir = String.format(pattern, basePath, UUIDUtils.random()); File file = new File(testDir); try { Assert.assertTrue(file.mkdirs()); Set<PosixFilePermission> permissions = getPosixFilePermissions(testDir); System.out.println(PosixFilePermissions.toString(permissions)); FileUtils.changePermission(file); permissions = getPosixFilePermissions(testDir); System.out.println(PosixFilePermissions.toString(permissions)); Assert.assertTrue(permissions.contains(PosixFilePermission.OWNER_WRITE)); Assert.assertTrue(permissions.contains(PosixFilePermission.OWNER_READ)); Assert.assertTrue(permissions.contains(PosixFilePermission.GROUP_WRITE)); Assert.assertTrue(permissions.contains(PosixFilePermission.GROUP_READ)); Assert.assertTrue(permissions.contains(PosixFilePermission.OTHERS_WRITE)); Assert.assertTrue(permissions.contains(PosixFilePermission.OTHERS_READ)); } finally { Assert.assertTrue(file.delete()); } }
private Set<PosixFilePermission> getPosixFilePermissions(String testDir) throws IOException { PosixFileAttributeView posixView = Files.getFileAttributeView(Paths.get(testDir), PosixFileAttributeView.class); return posixView.readAttributes().permissions(); }
|
这篇文章也有详细的介绍:https://stackoverflow.com/questions/14325641/create-folders-programmatically-along-with-permissions-using-java-to-save-conten
扫码手机观看或分享: