在把数据库文件放在raw中,在应用程序中如何打开

时间:2022-08-19 19:29:17

1、DbManager代码

 package com.zyh.zyhimportdatabase;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream; import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment; public class DbManager {
private static final int BUFFER_SIZE = 1024;
private static final String DB_NAME = "person2.db";
private static final String PACKAGE_NAME = "com.zyh.zyhimportdatabase";
private static final String DB_PATH = "/data" +
Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME; private SQLiteDatabase database;
private Context context; public DbManager(Context context){
this.context = context;
} public void openDatabase(){
this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
} private SQLiteDatabase openDatabase(String dbFile) {
try {
File db_file = new File(dbFile);
if(!db_file.exists()){
InputStream is = this.context.getResources().openRawResource(R.raw.person2);
FileOutputStream fos = new FileOutputStream(dbFile);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while((len = is.read(buffer)) > 0){
fos.write(buffer, 0, len);
}
fos.close();
is.close();
} SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(db_file, null);
return db;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} public SQLiteDatabase getDb(){
return this.database;
} public void closeDatabase(){
this.database.close();
}
}

2、activity代码

 package com.zyh.zyhimportdatabase;

 import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Log.i("zyh", Environment.getDataDirectory().getAbsolutePath());
DbManager dbHelper = new DbManager(getApplicationContext());
dbHelper.openDatabase();
SQLiteDatabase db = dbHelper.getDb();
System.out.println(db.isReadOnly());
dbHelper.closeDatabase(); } }

上述代码的参考:http://www.cnblogs.com/xiaowenji/archive/2011/01/03/1925014.html

注意:A、关于对getReadableDatabase()的误区:可以参考http://blog.csdn.net/liuhe688/article/details/6715983/和http://blog.chinaunix.net/uid-22816738-id-3802353.html

B、关于多线程对db的使用,正确的方法可以参考:http://blog.csdn.net/sky_monkey/article/details/23820021