从资产复制数据库时出错

时间:2018-06-01 05:11:11

标签: java android

我的文件名为" word504.db"在我的资产文件夹中,并尝试将此文件复制到数据目录,以便我能够阅读它。

ALTER TABLE test_table ALTER COLUMN CREATED_DATE SET DEFAULT CURRENT_TIMESTAMP;

ALTER TABLE test_table ADD COLUMN CREATED_DATE_temp DEFAULT CURRENT_TIMESTAMP;

但是我在Logcat中遇到了这个错误:

  

/data/data/org.zanjan.words504/databases/word504.db:open failed:   ENOENT(没有这样的文件或目录)

提前致谢

1 个答案:

答案 0 :(得分:2)

试试这个

DataBaseHalper.class



 public static final String DATABASE_NAME = "recipe.db";
    public final static String DATABASE_PATH = "/data/data/"+ MobyiUtils.PACKAGE_NAME + "/databases/";
    public static final int DATABASE_VERSION = 1;

 public void createDatabase()  {
        boolean dbExist1 = checkDataBase();
        if (!dbExist1) {
            this.getReadableDatabase();
            try {
                this.close();
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    // Check database already exist or not
    private boolean checkDataBase() {
        boolean checkDB = false;
        try {
            String myPath = DATABASE_PATH + DATABASE_NAME;
            File dbfile = new File(myPath);
            checkDB = dbfile.exists();
        } catch (SQLiteException e) {
        }
        return checkDB;
    }

    // Copies your database from your local assets-folder to the just created
    // empty database in the system folder
    public void copyDataBase() throws IOException {
        String outFileName = DATABASE_PATH + DATABASE_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);
        InputStream myInput = mContext.getAssets().open(DATABASE_NAME);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        myInput.close();
        myOutput.flush();
        myOutput.close();
    }

MainActiviy.class

 helper = new DataBaseHelper(MainActivity.this);
        helper.createDatabase();
        helper.openDatabase();
        helper.close();