android导入外部已存在的数据库大于1M的数据库文件方法(转)

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

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 将把assets下的数据库文件直接复制到DB_PATH,但数据库文件大小限制在1M以下
 * 如果有超过1M的大文件,则需要先分割为N个小文件,然后使用copyBigDatabase()替换copyDatabase()
 */
public class DBManager extends SQLiteOpenHelper {
    // 用户数据库文件的版本
    private static final int DB_VERSION = 1;
    // 数据库文件目标存放路径为系统默认位置,com.rys.lb 是你的包名
    private static String DB_PATH = "/data/data/com.chishacai/";

    // 如果你想把数据库文件存放在SD卡的话
    // private static String DB_PATH =
    // android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
    // + "/arthurcn/drivertest/packfiles/";

    private static String DB_NAME = "cscpb.db";
    private static String ASSETS_NAME = "cscdb/cscpb.db";

    private SQLiteDatabase myDataBase;
    private final Context myContext;

    /**
     * 如果数据库文件较大,使用FileSplit分割为小于1M的小文件 此例中分割为 data.db.100 data.db.101
     * data.db.102....
     */
    // 第一个文件名后缀
    private static final int ASSETS_SUFFIX_BEGIN = 0;
    // 最后一个文件名后缀
    private static final int ASSETS_SUFFIX_END = 3;
    
    private static SQLiteDatabase credb ;

    /**
     * 在SQLiteOpenHelper的子类当中,必须有该构造函数
     * @param context 上下文对象
     * @param name 数据库名称
     * @param factory 一般都是null
     * @param version 当前数据库的版本,值必须是整数并且是递增的状态
     */
    public DBManager(Context context, String name, CursorFactory factory,
            int version) {
        // 必须通过super调用父类当中的构造函数
        super(context, name, null, version);
        this.myContext = context;
    }

    public DBManager(Context context, String name, int version) {
        this(context, name, null, version);
    }

    public DBManager(Context context, String name) {
        this(context, name, DB_VERSION);
    }

    public DBManager(Context context) {
        this(context, DB_PATH + DB_NAME);
    }

    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            // 数据库已存在,do nothing.

            System.out.println("数据库已经存在");

        } else {
            // 创建数据库
            try {
                File dir = new File(DB_PATH);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File dbf = new File(DB_PATH + DB_NAME);
                if (dbf.exists()) {
                    dbf.delete();
                }
                credb = SQLiteDatabase.openOrCreateDatabase(dbf, null);
                // 复制asseets中的db文件到DB_PATH下
                // copyDataBase();
                copyBigDataBase();
            } catch (IOException e) {
                throw new Error("数据库创建失败");
            }
        }
    }

    // 检查数据库是否有效
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        String myPath = DB_PATH + DB_NAME;
        try {
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            // database does't exist yet.
        }
        if (checkDB != null) {
            checkDB.close();
            System.out.println("关闭");
        }
        return checkDB != null ? true : false;
    }

    public DBManager open1() {
        String myPath = DB_PATH + DB_NAME;
        System.out.println("数据库已经...");
        myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);
        System.out.println("数据库打开");
        return this;

    }

    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException {
        // Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(ASSETS_NAME);
        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;
        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);
        // transfer bytes from the inputfile to the outputfile
        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();
    }

    // 复制assets下的大数据库文件时用这个
    private void copyBigDataBase() throws IOException {
        InputStream myInput;
        String outFileName = DB_PATH + DB_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);
        for (int i = ASSETS_SUFFIX_BEGIN; i < ASSETS_SUFFIX_END + 1; i++) {
            myInput = myContext.getAssets().open(ASSETS_NAME + "." + i);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }
            myOutput.flush();
            myInput.close();
        }
        myOutput.close();
        System.out.println("数据库已经复制");
    }
    
    /**
     * 关闭刚创建的数据库
     */
    public void closedb() {
        if(credb != null) {
            credb.close() ;
            System.out.println("创建的数据库已关闭");
        }
    }

    @Override
    public synchronized void close() {
        if (myDataBase != null) {
            myDataBase.close();
            System.out.println("关闭成功1");
        }
        super.close();
        System.out.println("关闭成功2");
    }

    /**
     * 该函数是在第一次创建的时候执行, 实际上是第一次得到SQLiteDatabase对象的时候才会调用这个方法
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    /**
     * 数据库表结构有变化时采用
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public void open() {
        SQLiteDatabase DataBase = this.openOrCreateDatabase("data.db",

        null);
    }

    private SQLiteDatabase openOrCreateDatabase(String string, Object object) {
        // TODO Auto-generated method stub
        return null;
    }

}

 

改了一点点东西,代码的注释就能看懂。

1.如果数据库文件大于1M,就用Filesplit工具切割。先去下载这个软件工具
2.首先把已有的数据库放到assets文件夹下面,如果没有这个文件就先在android项目中建立这个文件夹。

转载于:https://www.cnblogs.com/jinglingJuly/archive/2013/05/04/3059032.html

CSDN海神之光上传的代码均可运行,亲测可用,直接替换数据即可,适合小白; 1、代码压缩包内容 主函数:main.m; 调用函数:其他m文件;无需运行 运行结果效果图; 2、代码运行版本 Matlab 2019b或2023b;若运行有误,根据提示修改;若不会,私信博主; 3、运行操作步骤 步骤一:将所有文件放到Matlab的当前文件夹中; 步骤二:双击打开main.m文件; 步骤三:点击运行,等程序运行完得到结果; 4、仿真咨询 如需其他服务,可私信博主或扫描博客文章底部QQ名片; 4.1 博客或资源的完整代码提供 4.2 期刊或参考文献复现 4.3 Matlab程序定制 4.4 科研合作 功率谱估计: 故障诊断分析: 雷达通信:雷达LFM、MIMO、成像、定位、干扰、检测、信号分析、脉冲压缩 滤波估计:SOC估计 目标定位:WSN定位、滤波跟踪、目标定位 生物电信号:肌电信号EMG、脑电信号EEG、心电信号ECG 通信系统:DOA估计、编码译码、变分模态分解、管道泄漏、滤波器、数字信号处理+传输+分析+去噪(CEEMDAN)、数字信号调制、误码率、信号估计、DTMF、信号检测识别融合、LEACH协议、信号检测、水声通信 1. EMD(经验模态分解,Empirical Mode Decomposition) 2. TVF-EMD(时变滤波的经验模态分解,Time-Varying Filtered Empirical Mode Decomposition) 3. EEMD(集成经验模态分解,Ensemble Empirical Mode Decomposition) 4. VMD(变分模态分解,Variational Mode Decomposition) 5. CEEMDAN(完全自适应噪声集合经验模态分解,Complementary Ensemble Empirical Mode Decomposition with Adaptive Noise) 6. LMD(局部均值分解,Local Mean Decomposition) 7. RLMD(鲁棒局部均值分解, Robust Local Mean Decomposition) 8. ITD(固有时间尺度分解,Intrinsic Time Decomposition) 9. SVMD(逐次变分模态分解,Sequential Variational Mode Decomposition) 10. ICEEMDAN(改进的完全自适应噪声集合经验模态分解,Improved Complementary Ensemble Empirical Mode Decomposition with Adaptive Noise) 11. FMD(特征模式分解,Feature Mode Decomposition) 12. REMD(鲁棒经验模态分解,Robust Empirical Mode Decomposition) 13. SGMD(辛几何模态分解,Spectral-Grouping-based Mode Decomposition) 14. RLMD(鲁棒局部均值分解,Robust Intrinsic Time Decomposition) 15. ESMD(极点对称模态分解, extreme-point symmetric mode decomposition) 16. CEEMD(互补集合经验模态分解,Complementary Ensemble Empirical Mode Decomposition) 17. SSA(奇异谱分析,Singular Spectrum Analysis) 18. SWD(群分解,Swarm Decomposition) 19. RPSEMD(再生相移正弦辅助经验模态分解,Regenerated Phase-shifted Sinusoids assisted Empirical Mode Decomposition) 20. EWT(经验小波变换,Empirical Wavelet Transform) 21. DWT(离散小波变换,Discraete wavelet transform) 22. TDD(时域分解,Time Domain Decomposition) 23. MODWT(最大重叠离散小波变换,Maximal Overlap Discrete Wavelet Transform) 24. MEMD(多元经验模态分解,Multivariate Empirical Mode Decomposition) 25. MVMD(多元变分模态分解,Multivariate Variational Mode Decomposition)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值