java 更改linux上的檔案使用者和組
阿新 • • 發佈:2021-01-01
java建立檔案放在linux伺服器上預設的都是root root,有時需要修改檔案的組和使用者
// 設定使用者和組,相當於linux命令chown // 要保證使用者和組存在,否則lookupService會拋UserPrincipalNotFoundException UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService(); //yw 要切換的組名 GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName("yw"); //yw 要切換的使用者名稱 UserPrincipal userPrincipal = lookupService.lookupPrincipalByName("yw"); //檔名地址 Path path = Paths.get("H:/360-phone/20201231/cwj_alllb-ss_20201231.csv"); PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class); view.setGroup(groupPrincipal); view.setOwner(userPrincipal);
修改完成後: