Android: check if the file is a valid SQLite database

I need to check if a file (with unknown extension) is a valid SQLite database. The db file is stored on the SD card. I need to import a database into my application. But if the user creates a file with the same name as in the database with any extension, the file is still accepted by the code when searching only for the name. Is there a quick way to check if sqlite db stored on a memory card is working correctly. I used this code, but it still accepts an arbitrary file with the 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}
+4
source share
1 answer

SQLite , . , SQlite 16 : SQLite 3\0000

, , 16 :

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;
    }
}
+4

Source: https://habr.com/ru/post/1655087/


All Articles