导入压缩后的数据库

直接复制db文件一般会比较大,先压缩下是个不错的办法,下面是对压缩后的db文件进行解压缩并复制到/data/data/package name/databases/下.

protected static void copyZip(Activity activity)//复制zip压缩文件
	{
		String DATABASE_PATH = "/data/data/cn.edu.seu.lx.info/databases/";
		String dbName = "seu.db";
		String zipName = "seu.zip";
		String dbFileName = DATABASE_PATH + dbName;

		boolean isDbExist = false;
		SQLiteDatabase checkDB = null;
		try {
			checkDB = SQLiteDatabase.openDatabase(dbFileName, null,SQLiteDatabase.NO_LOCALIZED_COLLATORS);
		}
		catch (SQLException e) {
			Log.d("copyZipDB", "SQLiteException catch:" + e.toString());
		}
		catch (Exception e) {
			Log.d("copyZipDB", "other Exception1 catch:" + e.toString());
		}
		finally {
			if (checkDB != null) {
				isDbExist = true;
				checkDB.close();
			}
		}
		if (!isDbExist)// 数据库不存在则拷贝
		{
			Log.e("copyZipDB", "db is NOT exist");
			File dir = new File(DATABASE_PATH);
			if (!dir.exists())// 判断数据库文件夹是否存在,不存在则新建
				dir.mkdir();
			InputStream input = null;
			try {
				input = activity.getAssets().open(zipName);
				Unzip(input, DATABASE_PATH);//调用下面的Unzip方法
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	private static void Unzip(InputStream input, String targetDir)
	{  //参数一为源zip文件的完整路径,参数二为解压缩后存放的文件夹(不是文件)。
		int BUFFER = 8192;// 这里缓冲区我们使用8KB,
		String strEntry; // 保存每个zip的条目名称
		try {
			BufferedOutputStream dest = null; // 缓冲输出流
			//FileInputStream fis = new FileInputStream(zipFile);
			ZipInputStream zis = new ZipInputStream(input);
			ZipEntry entry; // 每个zip条目的实例
			while ((entry = zis.getNextEntry()) != null) {
				try {
					Log.i("Unzip: ", "" + entry);
					int count;
					byte data[] = new byte[BUFFER];
					strEntry = entry.getName();

					File entryFile = new File(targetDir + strEntry);
					File entryDir = new File(entryFile.getParent());
					if (!entryDir.exists()) {
						entryDir.mkdirs();
					}

					FileOutputStream fos = new FileOutputStream(entryFile);
					dest = new BufferedOutputStream(fos, BUFFER);
					while ((count = zis.read(data, 0, BUFFER)) != -1) {
						dest.write(data, 0, count);
					}
					dest.flush();
					dest.close();
				}
				catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			zis.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

参考:http://www.android123.com.cn/androidkaifa/822.html


你可能感兴趣的:(Android)