In the Android systemProgramThe data is stored in the/data/(package name)/directory, and the database is under the/dabases/directory ..
Therefore, you only need to use fileinputstream to read the original database, and then use fileoutputstream to write the read content to that directory ..
Operation Method: 1. Include the original database in the Res/raw directory of the project source code.
2. Create a class to control the database... as follows:
Public Class Databasemanager {
Private Final Int Buffer_size = 400000;
Public Static Final String db_name = "mydatabase. DB "; // Name of the saved database file
Public Static Final String package_name = "com. Android. importdbtest "; // Package name
Public Static Final String db_path = "/Data"
+ Environment. getdatadirectory (). getabsolutepath () + "/"
+ Package_name; // Location where the database is stored on the mobile phone
Private Sqlitedatabase database;
Private Context context;
Dbmanager (context ){
This. Context = context;
}
Public VoidOpendatabase (){
This. Database =This. Opendatabase (db_path + "/" + db_name );
}
Private Sqlitedatabase opendatabase (string dbfile ){
Try {
If (! ( New File (dbfile). exists ())){ // Determines whether the database file exists. If it does not exist, import the database. Otherwise, open the database directly.
Inputstream is = This . Context. getresources (). openrawresource (
R. Raw. mydatabase ); // Database to be imported
Fileoutputstream Fos = New Fileoutputstream (dbfile );
Byte [] Buffer = New Byte [Buffer_size];
Int Count = 0;
While (COUNT = is. Read (buffer)> 0 ){
FOS. Write (buffer, 0, count );
}
FOS. Close ();
Is. Close ();
}
Sqlitedatabase DB = sqlitedatabase. openorcreatedatabase (dbfile,
Null );
Return DB;
} Catch (Filenotfoundexception e ){
Log. E ("Database", "file not found ");
E. printstacktrace ();
} Catch (Ioexception e ){
Log. E ("Database", "Io exception ");
E. printstacktrace ();
}
Return Null ;
}
Then, when you need to use the database, instantiate a databasemanager class and call its opendatabase method to return a sqlitedatabase object:
Sqlitedatabase DB = New Dbmanager ( This ). Opendatabase ();