W / System.err:java.io.FileNotFoundException:访问存储在Assets文件夹中的数据库

时间:2015-12-11 04:20:37

标签: java android android-assets

我是Android的初学者,使用现有的数据库开发一个简单的应用程序。我发现我无法直接使用它,并且必须先将其复制到本地数据目录,然后再对其执行查询[/ data / data /]。我已经声明了读取和写入权限,因为有些人建议访问存储在assets文件夹中的数据库。

现在,针对问题:我无法访问存储在Assets文件夹中的数据库。我尝试过AssetDatabaseOpenHelper()等等。所有这些都表明我复制了我无法做到的数据库。我在下面发布了我的代码:

package com.vrsit.myfriendsapp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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

public class DBHandler extends SQLiteOpenHelper {

    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.vrsit.myfriendsapp/databases/";

    // Database Name
    private static String DB_NAME = "vrs.db";

    // Logcat tag
    private static final String LOG = "database";

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

    // Database Name
    private static final String DATABASE_NAME = "vrs.db";
    private SQLiteDatabase myDataBase;

    private final Context myContext;

    public static long INSERT_ERROR = -1;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     *
     * @param context
     */
    public DBHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.myContext = context;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own database.
     */
    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 {
            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            Log.d(LOG, "!!!Creating Empy Database!!!");
            this.getReadableDatabase();
            this.close();

            Log.d(LOG, "!!!Coping Database!!!");
            copyDataBase();

        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    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't exist yet");
        }

        if(checkDB != null){
            checkDB.close();
        }
        return checkDB != null ? true : false;*/
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     */
    private void copyDataBase() {
        Log.d("LOG", "Input Entered");

        //Open your local db as the input stream
        try {
            Log.d("LOG", "Input Found");
            InputStream myInput = myContext.getAssets().open(DB_NAME, 3);


            // 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
            File out = new File(outFileName);
            out.setWritable(true);
            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();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }


    public void openDataBase() throws SQLException {
        openDataBase(true);
    }

    public void openDataBase(boolean readonly) throws SQLException {
        //Open the database
        String myPath = DB_PATH + DB_NAME;

        if (readonly)
            myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        else
            myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public synchronized void close() {
        if (myDataBase != null)
            myDataBase.close();

        super.close();
    }

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

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

1 个答案:

答案 0 :(得分:1)

这种方式让我可以使用资产文件夹中保存的数据库。

public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        DB_PATH = context.getDatabasePath(DatabaseHelper.DB_NAME).toString()
                .replace(DB_NAME, "");
        this.mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        database = db;
        String CREATE_TABLE = "CREATE TABLE QUERY";
        database.execSQL(CREATE_LOCATION_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        database = db;

    }

    public boolean createDatabase() {
        boolean isExist = checkDBExists();
        if (isExist) {
            System.out.println("DB Exists...");
            openDatabase();
            onUpgrade(database, database.getVersion(), DB_VERSION);
            close();
        } else {
            System.out.println("Copying DB...");
            this.getReadableDatabase();
            copyDatabase();
        }

        return isExist;
    }

    private boolean checkDBExists() {
        try {
            File file = new File(DB_PATH + DB_NAME);
            if (file.exists()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return false;
    }

    private void copyDatabase() {
        try {
            InputStream is = mContext.getAssets().open("databases/" + DB_NAME);
            OutputStream fos = new FileOutputStream(DB_PATH + DB_NAME);

            int length = 0;
            byte[] buffer = new byte[1024];

            while ((length = is.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }

            fos.flush();
            fos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void openDatabase() {
        database = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    public synchronized void close() {
        if (database != null)
            database.close();
        SQLiteDatabase.releaseMemory();
        super.close();
    }