在Android java程式碼中如何改變檔案的許可權
在LINUX下每個檔案都有一個許可權的屬性 ,那麼在Android中怎麼用java改變某個檔案的許可權呢?
Android中有兩種方法可以改變檔案的許可權
1. 用openFileOutput方法:
- FileOutputStream fos;
- fos = openFileOutput("filename", MODE_WORLD_READABLE);
Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.
可用的mode 引數如下:
/**
* File creation mode: the default mode, where the created file can only
* be accessed by the calling application (or all applications sharing the
* same user ID).
* @see #MODE_WORLD_READABLE
* @see #MODE_WORLD_WRITEABLE
*/
public static final int MODE_PRIVATE = 0x0000;
/**
* File creation mode: allow all other applications to have read access
* to the created file.
* @see #MODE_PRIVATE
* @see #MODE_WORLD_WRITEABLE
*/
public static final int MODE_WORLD_READABLE = 0x0001;
/**
* File creation mode: allow all other applications to have write access
* to the created file.
* @see #MODE_PRIVATE
* @see #MODE_WORLD_READABLE
*/
public static final int MODE_WORLD_WRITEABLE = 0x0002;
/**
* File creation mode: for use with {@link #openFileOutput}, if the file
* already exists then write data to the end of the existing file
* instead of erasing it.
* @see #openFileOutput
*/
public static final int MODE_APPEND = 0x8000;
其實該方法最終還是呼叫了系統的chmod來實現的改變檔案許可權的功能。
但是該方法有侷限性,他建立的檔案只能位於該程式的私有目錄下,即/data/data/app-package/files/
2. 用Runtime.getRuntime().exec()
- Runtime.getRuntime().exec("chmod 644 " + filename);
該方法呼叫系統命令chmod來改變檔案的許可權,為了能判斷命令的返回值,最好寫成:
-
Process p = Runtime.getRuntime().exec("chmod 644 " + filename);
- int status = p.waitFor();
- if (status == 0) {
- //chmod succeed
- } else {
- //chmod failed
- }