android 读取本地数据库db文件(Android sqlite)
在Android中,您可以使用SQLiteOpenHelper
类来读取assets目录下的SQLite数据库文件并将其复制到您的应用的数据目录中,以便您可以访问它。以下是一个简单的例子:
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_NAME = "your_database_name.db";
private static int DB_VERSION = 1;
private final Context mContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if(dbExist){
//数据库已存在,不需要创建
} else {
//创建数据库
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("ErrorCopyingDataBase");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = mContext.getDatabasePath(DB_NAME).getPath();
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
//打开assets目录下的数据库
InputStream myInput = mContext.getAssets().open(DB_NAME);
//路径:数据库将被创建的位置
String outFileName = mContext.getDatabasePath(DB_NAME).getPath();
//打开输出流
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the input file to the output file
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();
}
//添加其他数据库操作方法...
}
使用这个DatabaseHelper
类,您可以在需要的时候调用createDataBase
方法来复制并读取assets目录下的数据库文件。记得在AndroidManifest.xml
中添加读取assets文件夹的权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
并且,从Android 6.0(API 23)开始,您需要在运行时请求存储权限,以避免\`Fil
评论已关闭