当我们在开发应用的时候,有的时候需要给将一些文件随这应用的启动拷贝到内存卡或者系统应用中
最常见的就是数据库的拷贝
思路 :1、读取到数据的输入流
2、获取终点地址
3、将输入流转换为输出流,写到应用中
- public class DBuitls {
- private static final String TAG = "DBuitls";
- public static final String DB_NAME = "city.db";
- public static final int DB_VERSION = 1;
- private DBuitls() {
- super();
- }
- private static boolean extractDatabase(Context context, String name) {
- boolean retVal = false;
- // 获得数据存储的位置 ----/data/data/com.metek.copy/databases/city.db
- File db = context.getDatabasePath(name);
- if (!db.exists()) {
- File directory = db.getParentFile();
- directory.mkdirs();
- if (directory.exists()) {
- try {
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(db));
- InputStream in = context.getResources().openRawResource(R.raw.city);
- byte[] buf = new byte[1024 * 8];
- int length = 0;
- while (-1 != (length = in.read(buf))) {
- bos.write(buf, 0, length);
- }
- in.close();
- bos.close();
- retVal = true;
- } catch (FileNotFoundException ex) {
- Log.e(TAG, "Can not access db file.", ex);
- } catch (IOException ex) {
- Log.e(TAG, "Access db error.", ex);
- }
- } else {
- Log.e(TAG, "Can not make db directory.");
- }
- } else {
- retVal = true;
- }
- if (!retVal) {
- Log.e(TAG, "extractDatabase error");
- if (db.exists()) {
- db.delete();
- }
- }
- return retVal;
- }
- private static class PresetDbHelper extends SQLiteOpenHelper {
- public PresetDbHelper(Context context, String name) {
- super(context, name, null, 100);
- DBuitls.extractDatabase(context, name);
- }
- public void onCreate(SQLiteDatabase db) {
- Log.e(TAG, "This should never been called.");
- }
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- Log.e(TAG, "This should never been called.");
- }
- }
- public static int getDBcount(Context context) {
- PresetDbHelper dbOpenHelper = new PresetDbHelper(context, DB_NAME);
- SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
- String sql = "select count(*) from city";
- Cursor cursor = database.rawQuery(sql, null);
- int result = 0;
- if (cursor != null) {
- if (cursor.moveToNext()) {
- result = Integer.parseInt(cursor.getString(0));
- }
- cursor.close();
- }
- database.close();
- return result;
- }
- }
- <pre name="code" class="java">
- public class MainActivity extends Activity {
- private static final String TAG = null;
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- int count = DBuitls.getDBcount(this);
- TextView text = (TextView) findViewById(R.id.count);
- Log.i(TAG, "查询到数据库发长度是 :" + count);
- text.setText("查询到数据库的长度是:" + count);
- }
- }