Android:检查文件是否为有效的SQLite数据库 [英] Android: Check if a file is a valid SQLite database

查看:133
本文介绍了Android:检查文件是否为有效的SQLite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查文件(扩展名未知)是否为有效的SQLite数据库。
db文件存储在sd卡中。我需要在我的应用程序中导入数据库。但是,如果用户使用与扩展名相同的数据库名称来创建文件,则该代码仍会被代码接受,因为它仅搜索名称。
有没有一种快速的方法来检查存储卡中存储的sqlite db的有效性。
我使用了此代码,但它仍接受与db名称相同的任意文件。

I need to check whether a file (with unknown extension) is a valid SQLite database. The db file is stored on the sd card. I need to import the database in my app. But if the user creates a file by the same name as of the database with any extension the file is still accepted by the code as it searches only for the name. Is there a quick way to check for the validity of sqlite db stored on memory card. I used this code, but it still accepts arbitrary file with same name as db.

String path = Environment.getExternalStorageDirectory().getPath() + "/FOLDER/DB_FILE";

        SQLiteDatabase database;
        database = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
        if (database == null) {
            Toast.makeText(getApplicationContext(), "Error: Incorrect/Corrupted File", Toast.LENGTH_SHORT).show();
            return;
        } else {Proceed with code here}


推荐答案

一个SQLite数据库文件包含一个标题,该标题提供了一些有用的信息
特别是,每个SQlite数据库文件始终在其前16个字节中包含以下值: SQLite格式3\0000

A SQLite database file contains a header which provides some useful information. In particular, every SQlite database file has always in it's first 16 bytes the value: SQLite format 3\0000

因此您可以检查文件的前16个字节是否包含该值:

So you can check if your file contains that value in its first 16 bytes:

public boolean isValidSQLite(String dbPath) {
    File file = new File(dbPath);

    if (!file.exists() || !file.canRead()) {
        return false;
    }

    try {
        FileReader fr = new FileReader(file);
        char[] buffer = new char[16];

        fr.read(buffer, 0, 16);
        String str = String.valueOf(buffer);
        fr.close();

        return str.equals("SQLite format 3\u0000");

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

这篇关于Android:检查文件是否为有效的SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆