两种对数据库拷贝到手机内存的操作:
1.copy数据库到assets目录下,然后copy到sdCard上
2.copy数据库到src下,然后用类加载器copy到sdCard上
第一种方式代码:
// 判断这个common.db的数据库是否被放置到sd卡上
// 如果不在sd卡就把db从asset目录拷贝到数据库
File file = new File("/sdcard/commonnum.db");
if (!file.exists()) {
coppyFile();
}
private void coppyFile() {
// 如果不在sd卡就把db从asset目录拷贝到数据库
// 下面是文件拷贝操作
AssetManager manager = getAssets();
try {
InputStream is = manager.open("commonnum.db");
File file = new File("/sdcard/commonnum.db");
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
第二种方式代码:
// 判断手机内存是否存在这数据库
File file = new File(
"/data/data/com.example.clearsd/files/name/clearpath.db");
if (!file.exists()) {
coppyFile();
}
public void coppyFile() {
try {
InputStream is = getClass().getClassLoader().getResourceAsStream(
"clearpath.db");
OutputStream fos = this.openFileOutput(
"/data/data/com.example.clearsd/files/name/clearpath.db",
MODE_PRIVATE);// 文件写到data/data/cn.itcast.clear/file/name
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}