从资产中读取指向错误的路径?

Reading from assets directs to wrong path?

我正在尝试使用 sqlite 助手 class, 我的 db_map 在 /assets 文件夹中。 sqlite 助手应该将它从那里复制到 data/data/com.package.app/databases/

我得到了 FileNotFound exception

调试和使用时assetManager.list("")。 我发现列表中有 "images""sounds""webkit" 个文件。 奇怪的是我没有这些,只有我的 db_map 文件。

代码:

AssetManager assetManager = context.getResources().getAssets();
myInput = assetManager.open("db_map");

首先 您需要在目的地创建一个数据库。之后你可以复制它的顶部。

所以。这是我用的。

我创建了一个从 SQLiteOpenHelper

扩展的 class 数据库

在此class中,我执行以下操作。

// Database Version
private static final int DB_VERSION = 1;

// Database Name
private static String DB_NAME = "DB.sqlite";

//The default system path of your application database.
private static String DB_PATH = "/data/data/com.namespace.xxx/databases/";

public Database(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    this.myContext = context;
}   

public void createDataBase() throws IOException{

    Log.d(LOG, "Calling checkDataBase() Method");

    boolean dbExist = checkDataBase();

    if(dbExist){
        //do nothing - database already exist
        Log.d(LOG, "!!!Database Found!!!");
    }else{
        //Empty database will be created into the default system path
        Log.d(LOG, "!!!Creating Empy Database!!!");
        this.getReadableDatabase();
        this.close();
        try {
            Log.d(LOG, "!!!Coping Database!!!");
            copyDataBase();
        } catch (IOException e) {
            throw new Error(e);
        }
    } 
}

private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{
        String myPath = DB_PATH + DB_NAME;

        Log.d(LOG, "looking database at " + myPath);

        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){
        //database does't exist yet.
        Log.e(LOG, "Exception: database does not exist yet");
    }

    if(checkDB != null){
        checkDB.close();
    }
    return checkDB != null ? true : false;
}

// Copies your database from your local assets-folder
// to the created empty database
private void copyDataBase() throws IOException{
    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    Log.d(LOG, "Coping database from " + myInput + ", to " + outFileName);

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

祝你好运。