Java 如何在android中以编程方式更改文件/文件夹权限

Java 如何在android中以编程方式更改文件/文件夹权限,java,android,file-permissions,chmod,fileutils,Java,Android,File Permissions,Chmod,Fileutils,如果正在存储应用程序数据库,我想更改文件夹的权限。 在谷歌上搜索后,我发现:- 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,

如果正在存储应用程序数据库,我想更改文件夹的权限。

在谷歌上搜索后,我发现:-

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);
...
这里的
FileUtils
类应该是
android.os
包的一部分,但是我在导入包时找不到它

您知道如何使用
FileUtils
或其他方法更改文件夹的权限吗

我正在更改权限,因为在安装应用程序后,当我尝试访问数据库时,应用程序停止工作。由于我的设备是
根目录
,因此当我使用
根目录浏览器将数据库文件夹的权限从
771
更改为
777
时,应用程序开始正常工作。

那么,如何在安装应用程序时更改文件夹的权限,即在
unrooted
设备中以编程方式

My
DBHelper
类:-

public class DBHelper extends SQLiteOpenHelper {

public SQLiteDatabase database = null;
public File databaseFile;
public static String databaseName = "Db1.sqlite";
public String databasePath = "";
Context mContext;

public DBHelper(Context paramContext) {

    super(paramContext, databaseName, null, 1);
    this.mContext = paramContext;

    Log.d("data", "package name:" + paramContext.getPackageName());

    //this.databasePath = ("data/data/" + paramContext.getPackageName() + "/databases/"+databaseName);
    this.databasePath = (Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/data/"+paramContext.getPackageName()+"/"+databaseName);
    System.out.println(databasePath);
    this.databaseFile = new File(this.databasePath);
    if (!this.databaseFile.exists())
        try {
            deployDataBase(DBHelper.databaseName, this.databasePath);
            return;
        } catch (IOException localIOException) {
            localIOException.printStackTrace();
        }
}

private void deployDataBase(String dbNAme, String dbPath)
        throws IOException {
    InputStream localInputStream = this.mContext.getAssets().open(dbNAme);
    FileOutputStream localFileOutputStream = new FileOutputStream(dbPath);
    byte[] arrayOfByte = new byte[1024];
    while (true) {
        int i = localInputStream.read(arrayOfByte);
        if (i <= 0) {
            localFileOutputStream.flush();
            localFileOutputStream.close();
            localInputStream.close();
            return;
        }
        localFileOutputStream.write(arrayOfByte, 0, i);
    }
}

@Override
public synchronized void close() {

    if (database != null)
        database.close();

    super.close();

}
@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

}
public类DBHelper扩展了SQLiteOpenHelper{
公共SQLiteDatabase=null;
公共文件数据库文件;
公共静态字符串databaseName=“Db1.sqlite”;
公共字符串databasePath=“”;
语境;
公共DBHelper(上下文参数上下文){
super(paramContext,databaseName,null,1);
this.mContext=paramContext;
Log.d(“数据”,“包名:”+paramContext.getPackageName());
//this.databasePath=(“data/data/”+paramContext.getPackageName()+“/databases/”+databaseName);
this.databasePath=(Environment.getExternalStorageDirectory().getAbsolutePath()+“/Android/data/”+paramContext.getPackageName()+“/”+databaseName);
System.out.println(数据库路径);
this.databaseFile=新文件(this.databasePath);
如果(!this.databaseFile.exists())
试一试{
部署数据库(DBHelper.databaseName,this.databasePath);
返回;
}捕获(IOException localIOException){
localIOException.printStackTrace();
}
}
私有数据库(字符串dbNAme、字符串dbPath)
抛出IOException{
InputStream LocaliInputStream=this.mContext.getAssets().open(dbNAme);
FileOutputStream localFileOutputStream=新的FileOutputStream(dbPath);
字节[]数组字节=新字节[1024];
while(true){
int i=localInputStream.read(arrayOfByte);
如果(i
  • 不要使用您案例的db路径和文件权限

  • IMO和普通设备是相互排斥的受众

  • 仅用于测试根设备,在sd卡上创建db,路径派生自Environment.getExternalStorage**方法

要在SD卡上安装数据库,请执行以下操作

将该类放入代码包中

package com.test.db;

import java.io.File;

import android.content.Context;
import android.content.ContextWrapper;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.os.Environment;

/** 
 * Custom context wrapper to proxy the database file path.
 * Instead of storing data on internal storage for app
 * we will storing the data on external sd card.
 */
public class DatabaseContext extends ContextWrapper {

    /*
     * Used for logging.
     */
    private static final String DEBUG_CONTEXT = "DatabaseContext";

    /*
     * Constructor wrapping given app context.
     */
    public DatabaseContext(Context base) {
        super(base);
    }

    /**
     * Proxy the path to data base file for every operation
     * @see android.content.ContextWrapper#getDatabasePath(java.lang.String)
     */
    @Override
    public File getDatabasePath(String name) {

        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            File sdcard = Environment.getExternalStorageDirectory();
            String dbfile = sdcard.getAbsolutePath() + File.separator + "com.test" +     File.separator + "database" + File.separator
                + name;
            if (!dbfile.endsWith(".db")) {
                dbfile += ".db";
            }

            File result = new File(dbfile);

            if (!result.getParentFile().exists()) {
                if(!result.getParentFile().mkdirs()){
                    result = new File(sdcard, name);
                }
            }

            if (android.util.Log.isLoggable(DEBUG_CONTEXT, android.util.Log.WARN)) {
                android.util.Log.w(DEBUG_CONTEXT,
                    "getDatabasePath(" + name + ") = " + result.getAbsolutePath());
            }

            return result;

        } else {
            // Something else is wrong. It may be one of many other states,
            // Writing data on internal storage
            return super.getDatabasePath(name);
        }

    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode,
            CursorFactory factory) {
        return openOrCreateDatabase(name, mode, factory, null);
    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory,
        DatabaseErrorHandler errorHandler) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name)
            .getAbsolutePath(), null, errorHandler);

        return result;
    }
}
像这样扩展SqliteOpenHelper类

package com.test.db;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

import android.content.Context; 
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Custom SqliteOpenHelper.
 */
public class MySQLiteOpenHelper extends SQLiteOpenHelper {

    private static final String TAG = My.class.getSimpleName();

    private final Context context;

    public  MySQLiteOpenHelper(Context context, String name, int version, String mResourceName) {
        super(new DatabaseContext(context), name, /*factory*/null, version);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      // Create tables here
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

}

这是在sd卡中创建db的测试件。请检查

您正在玩一个危险的游戏。@SotiriosDelimanolis但如果我不这样做,我如何解决我的问题?您的db没有在外部sd卡中定义?@Javanator如果设备没有外部sd卡怎么办?现在大多数设备没有外部存储插槽,但有ex内部存储作为内部存储的模拟分区我使用了
Environment.getExternalStorageDirectory().getAbsolutePath()+“/Android/data/”+paramContext.getPackageName()+“/”+databaseName
作为存储我的
db
的路径,但我在那里看不到它:(在此处打印完整路径/storage/sdcard/Android/data/com.test/Db1.sqlite应用程序出现异常:-
java.io.FileNotFoundException:/storage/sdcard/Android/data/com.test/Db1.sqlite:open failed:enoint(没有此类文件或目录)
因为那里没有文件。你必须创建它。检查上面的代码段。它会帮你完成。