在開發中,有時須要使用db文件數據庫。所以就須要將其導入項目,再將其使用程序寫入到應用的db文件下使用。
代碼非常easy。能夠拿來直接使用。
要使用須要兩個步驟:
1.創建raw文件。導入db文件。例如以下:

2.代碼
public class DBOpenHelper {
private final int BUFFER_SIZE = 400000;
public static final String DB_NAME = "idiom.db"; // 保存的數據庫文件名稱
public static final String PACKAGE_NAME = "cn.edu.bzu.happy";// 應用的包名
public static final String DB_PATH = "/data"
+ Environment.getDataDirectory().getAbsolutePath() +"/"
+ PACKAGE_NAME+ "/databases"; // 在手機里存放數據庫的位置
//sdcard的路徑(在android 4.4中不好使,文件成功創建是在手機的)
//public static final String DB_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()+"/idiom";
private Context context;
public DBOpenHelper(Context context) {
this.context = context;
}
public SQLiteDatabase openDatabase() {
try {
File myDataPath = new File(DB_PATH);
if (!myDataPath.exists())
{
myDataPath.mkdirs();// 假設沒有這個文件夾,則創建
}
String dbfile=myDataPath+"/"+DB_NAME;
if (!(new File(dbfile).exists())) {// 推斷數據庫文件是否存在,若不存在則運行導入,否則直接打開數據庫
InputStream is = context.getResources().openRawResource(
R.raw.idiom); // 欲導入的數據庫
FileOutputStream fos = new FileOutputStream(dbfile);
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
null);
return db;
} catch (FileNotFoundException e) {
Log.e("Database", "File not found");
e.printStackTrace();
} catch (IOException e) {
Log.e("Database", "IO exception");
e.printStackTrace();
}
return null;
}
}
使用:
public class TestDao {
private DBOpenHelper dbHelper;
public TestDao (Context context) {
dbHelper = new DBOpenHelper(context);
}
public List<Test> getAllTests() {
List<Test> animals = new ArrayList<Test>();
SQLiteDatabase sqLiteDatabase = dbHelper.openDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("select * from test", null);
While(cursor.moveToNext()){
//獲取你的數據
}
}
}
TestDao test = new TestDao(); test.getAllTests();
