android导入外部数据库

时间:2022-12-27 06:41:47


数据库文件必须放在res/raw文件夹下,否则会被压缩成二进制文件



 
 
public class TestActivity extends Activity {private SQLiteDatabase db;public SQLiteDatabase getDb() {db = openDatabase(TestActivity.this);return db;}private final static String DATABASE_PATH = android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + "/database";private static String DATABASE_FILENAME = "chinacity.db";// 使用外部数据库public SQLiteDatabase openDatabase(Context context) {try {// Context context=new TestActivity();String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;File dir = new File(DATABASE_PATH);if (!dir.exists()) // 如果文件夹不存在创建文件夹dir.mkdir();if (!(new File(databaseFilename)).exists()) { // 如果文件不存在创建文件InputStream is = context.getResources().openRawResource(R.raw.chinacity);FileOutputStream fos = new FileOutputStream(databaseFilename);byte[] buffer = new byte[8192];int count = 0;while ((count = is.read(buffer)) > 0) {fos.write(buffer, 0, count);}fos.close();is.close();}db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);} catch (Exception e) {e.printStackTrace();}return db;}@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.layout);System.out.println("数据库地址" + DATABASE_PATH);SQLiteDatabase db = openDatabase(TestActivity.this);System.out.println("数据库为===========" + db);}}