天天看點

Android 如何在java/native層修改一個檔案的權限(mode)與使用者(owner)?

前言

         歡迎大家我分享和推薦好用的代碼段~~

聲明

         歡迎轉載,但請保留文章原始出處:

         CSDN:

         雨季o莫憂離:

正文

[Description]

如何在java/native層修改一個檔案的權限(mode),使用者(owner),組(group),以滿足安全需要?

[Keyword]

檔案權限 檔案使用者 mode owner chomd chown permission

[Solution]

在native 層:

#include <sys/types.h>

#include <sys/stat.h>

#include <unistd.h>

//chmod/fchmod 用來更新通路權限

int chmod(const char *path, mode_t mode);

int fchmod(int fildes, mode_t mode);

//chown/fchown/lchown 用來更新檔案owner 和 group

int chown(const char *path, uid_t owner, gid_t group);

int fchown(int fd, uid_t owner, gid_t group);

int lchown(const char *path, uid_t owner, gid_t group);

//用來讀取檔案中繼資料

int stat(const char *path, struct stat *buf);

int fstat(int filedes, struct stat *buf);

int lstat(const char *path, struct stat *buf);

更多的資訊可以在linux 中 man chmod ; man chown ; man stat

在java 層:

java default 并不提供這樣的功能,android 為滿足内部需要,在android.os.FileUtils 類中提供了setPermissions 方法,結合了chmod 與chown. 參數中mode 即chmod 參數中的mode,當不需要設定file 的uid 和 group 時,可将uid 和 gid 都設定成-1;

android.os.FileUtils

public static native int setPermissions(String file, int mode, int uid, int gid);