ZipTool
public class ZipTool {
public static int openZip(Context context , String dataBasePath , String zipName){
int flag = 0;
try{
AssetManager am = context.getAssets();
ZipInputStream zis = new ZipInputStream(am.open(zipName));
FileOutputStream fos = new FileOutputStream(dataBasePath);
zis.getNextEntry();//读取下一个 ZIP 文件条目并将流定位到该条目数据的开始处。
byte[] buffer = new byte[1024];
int count = 0;
while ((count = zis.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.flush();
fos.close();
zis.close();
flag = 1;
}catch(Exception e){
flag = -1;
e.printStackTrace();
}
return flag;
}
}
SQLHelper
public class SQLHelper {
private SQLiteDatabase database;
private final String DATABASE_DIR = Environment.getExternalStorageDirectory() + "/test";
private final String ZIP_NAME = "test.zip";
private final String DATABASE_PATH = DATABASE_DIR+"/test.db";
private Context context ;
SQLHelper(Context context){
this.context = context;
}
/**
* 打开数据库连接
* @return SQLiteDatabase
*/
public SQLiteDatabase openDatabase(){
if(database != null && database.isOpen()){
return database;
}
try{
File file = new File(DATABASE_PATH);
//判断数据库文件是否存在
if(!file.exists()){
File dir = new File(DATABASE_DIR);
//判断数据库文件路径是否存在 , 不存在创建
if(!dir.exists()){
dir.mkdirs();
}
//解压ZIP文件
ZipTool.openZip(context, DATABASE_PATH, ZIP_NAME);
}
database = SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READWRITE);
}catch(Exception e){
e.printStackTrace();
}
return database;
}
}