public class TestSqlDatabase{
private static final String DATABASE_PATH = "/data/data/your.package.name/databases";
private static final int DATABASE_VERSION = 0;
private static final String DATABASE_NAME = "test.db";
private static String outFileName = DATABASE_PATH + "/" + DATABASE_NAME;
private Context context;
private SQLiteDatabase database;
public TestSqlDatabase(Context context) {
this.context = context;
File file = new File(outFileName);
if (file.exists()) {
database = SQLiteDatabase.openOrCreateDatabase(outFileName, null);
if (database.getVersion() != DATABASE_VERSION) {
database.close();
file.delete();
}
}
try {
buildDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
private void buildDatabase() throws Exception{
InputStream myInput = context.getResources().openRawResource(R.raw.test);
File file = new File(outFileName);
File dir = new File(DATABASE_PATH);
if (!dir.exists()) {
if (!dir.mkdir()) {
throw new Exception("创建失败");
}
}
if (!file.exists()) {
try {
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.close();
myInput.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}