其实也很简单
我们将准备好的数据库文件放到工程目录assets下,也就是可以一起打包的路径,然后将assets下的数据库文件复制一份到data/data/包名/databases/下面就行了,以下是核心代码:
private static final String DB_NAME = "abc.db"; // 数据库名
private static final String DATA_BASE_PATH = "/data/data/com.abc/databases/";
private static final int BUFFER_SIZE = 9000; // 根据数据库文件大小扩大
private void copyfile() {
File dir = new File(DATA_BASE_PATH);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(DATA_BASE_PATH + DB_NAME);
if (!file.exists()) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = mContext.getAssets().open(DB_NAME);
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = inputStream.read(buffer, 0, buffer.length)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}