将raw下的数据库文件导入到本地数据库

时间:2022-03-25 22:53:03
/**
* 将raw目录下的 数据库 加载到 数据库中
*/
private void copyDatabase() {
Thread thread = new Thread() {
@Override
public void run() {
copyRawDatabse(MemberActivity.this, "city.s3db", R.raw.city);
}
};
thread.start();
thread = null;
}


/*
* 将raw下的数据库文件导入到本地数据库
*/
public static boolean copyRawDatabse(Context context, String dataBaseName,
int fileID) {
boolean result = false;
String path = "/data"
+ Environment.getDataDirectory().getAbsolutePath() + "/"
+ "com.smarteroptimization" + "/databases";


System.out.println(path);
System.out.println(path + File.separator + dataBaseName);


File file = new File(path);
File file1 = new File(path + File.separator + dataBaseName);
file1.delete();
if (!(file1.exists())) { // 判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库
try {
InputStream is = context.getResources().openRawResource(fileID); // 欲导入的数据库
file.mkdirs();
file1.createNewFile();
FileOutputStream fos = new FileOutputStream(file1);
byte[] buffer = new byte[400000];
int count = -1;
while ((count = is.read(buffer)) != -1) {
fos.write(buffer, 0, count);
}
result = true;
is.close();
fos.close();
} catch (FileNotFoundException e) {
result = false;
Log.e("Database", "File not found");
e.printStackTrace();
} catch (IOException e) {
result = false;
Log.e("Database", "IO exception");
e.printStackTrace();
} catch (Exception e) {
result = false;
}
}
return result;
}