android导入外部数据库

数据库文件必须放在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;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout);
		System.out.println("数据库地址" + DATABASE_PATH);

		SQLiteDatabase db = openDatabase(TestActivity.this);
		System.out.println("数据库为===========" + db);
	}
}



你可能感兴趣的:(数据库,database,database,database)