2012-07-10 77 views
4

我知道它有可能改變使用文件的權限模式:如何獲取文件權限模式編程在Java中

Runtime.getRuntime().exec("chmod 777 myfile");

本示例將權限位設置爲777。是否可以使用Java以編程方式將權限位設置爲777?這可以做到每個文件?

+1

也許你可以在這篇文章中找到一些想法? : http://stackoverflow.com/questions/664432/how-do-i-programmatically-change-file-permissions – Silmarillium 2012-07-10 07:04:10

+0

內部Android使用'android.os.FileUtils',它像往常一樣,從SDK隱藏。但是,如果您不想調用'#exec(..)',則可以使用反射來訪問它。 – Jens 2012-07-10 07:17:01

回答

1

Android除了通過Intents外,很難與其他應用程序及其數據進行交互。意圖不會用於權限,因爲您依賴接收意圖的應用程序來執行/提供您想要的內容;他們可能沒有設計告訴任何人他們的文件的權限。有辦法可以解決這個問題,但只有當應用程序被設計爲在同一個JVM中運行時。 因此,每個應用程序只能更改它的文件。在文件權限詳見http://docs.oracle.com/javase/1.4.2/docs/guide/security/permissions.html

9

Android中

的Java使用chmod沒有像搭配chmod平臺相關業務的原生支持。但是,Android通過android.os.FileUtils爲這些操作提供了一些實用程序。 FileUtils類不是公共SDK的一部分,因此不受支持。因此,使用這種風險自負:

public int chmod(File path, int mode) throws Exception { 
Class fileUtils = Class.forName("android.os.FileUtils"); 
Method setPermissions = 
    fileUtils.getMethod("setPermissions", String.class, int.class, int.class, int.class); 
return (Integer) setPermissions.invoke(null, path.getAbsolutePath(), mode, -1, -1); 
} 

... 
chmod("/foo/bar/baz", 0755); 
... 

參考:http://www.damonkohler.com/2010/05/using-chmod-in-android.html?showComment=1341900716400#c4186506545056003185

+0

不僅它不是公共SDK API的一部分,而且它顯然是在**版本高於4.2.2的設備中被刪除**,根據:http://stackoverflow.com/questions/20858972/getting-java -lang-的NoSuchMethodError-Android的操作系統文件實用程序 - getfatvolumeid功能於4-2 – 2014-10-14 17:57:08

0

下面是使用Apache Commons.IO FileUtils的解決方案,並在File對象相應的方法。

for (File f : FileUtils.listFilesAndDirs(new File('/some/path'), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) { 
    if (!f.setReadable(true, false)) { 
     throw new IOException(String.format("Failed to setReadable for all on %s", f)); 
    } 
    if (!f.setWritable(true, false)) { 
     throw new IOException(String.format("Failed to setWritable for all on %s", f)); 
    } 
    if (!f.setExecutable(true, false)) { 
     throw new IOException(String.format("Failed to setExecutable for all on %s", f)); 
    } 
} 

這相當於chmod -R 0777 /some/path。調整set{Read,Writ,Execut}able調用以實現其他模式。 (如果有人發佈適當的代碼來做到這一點,我會很高興地更新這個答案。)

1

如前所述,android.os.FileUtils已更改,並且由Ashraf發佈的解決方案不再有效。以下方法應適用於所有版本的Android(儘管它使用反射,如果製造商做出重大更改,這可能無效)。

public static void chmod(String path, int mode) throws Exception { 
    Class<?> libcore = Class.forName("libcore.io.Libcore"); 
    Field field = libcore.getDeclaredField("os"); 
    if (!field.isAccessible()) { 
     field.setAccessible(true); 
    } 
    Object os = field.get(field); 
    Method chmod = os.getClass().getMethod("chmod", String.class, int.class); 
    chmod.invoke(os, path, mode); 
} 

很明顯,您需要擁有該文件才能進行任何權限更改。