Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> 將raw裡面的數據庫文件寫入到data中,rawdata

將raw裡面的數據庫文件寫入到data中,rawdata

編輯:關於android開發

將raw裡面的數據庫文件寫入到data中,rawdata


package com.city.list.db;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.city.list.main.R;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

/**
 * 將raw中得數據庫文件寫入到data數據庫中
 * @author sy
 *
 */
public class DBManager
{
    private final int BUFFER_SIZE = 400000;
    private static final String PACKAGE_NAME = "com.city.list.main";
    public static final String DB_NAME = "china_city_name.db";
    public static final String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME ; // 存放路徑
    private Context mContext;
    private SQLiteDatabase database;

    public DBManager(Context context)
    {
        this.mContext = context;
    }

    /**
     * 被調用方法
     */
    public void openDateBase()
    {
        this.database = this.openDateBase(DB_PATH + "/" + DB_NAME);

    }

    /**
     * 打開數據庫
     * 
     * @param dbFile
     * @return SQLiteDatabase
     * @author sy
     */
    private SQLiteDatabase openDateBase(String dbFile)
    {
        File file = new File(dbFile);
        if (!file.exists())
        {
            // 打開raw中得數據庫文件,獲得stream流
            InputStream stream = this.mContext.getResources().openRawResource(R.raw.china_city_name);
            try
            {
                // 將獲取到的stream 流寫入道data中
                FileOutputStream outputStream = new FileOutputStream(dbFile);
                byte[] buffer = new byte[BUFFER_SIZE];
                int count = 0;
                while ((count = stream.read(buffer)) > 0)
                {
                    outputStream.write(buffer, 0, count);
                }
                outputStream.close();
                stream.close();
                SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
                return db;
            } catch (FileNotFoundException e)
            {
                
                e.printStackTrace();
            } catch (IOException e)
            {
                
                e.printStackTrace();
            }
        }
        return database;
    }

    public void closeDatabase()
    {
        if (database != null && database.isOpen())
        {
            this.database.close();
        }
    }
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved