[Android] 导入外部数据库
参考
最初参考第一篇博文导入数据库,在虚拟机运行正常,但使用真机(华为)测试会报FileNotFoundException异常。经过一番查找,通过博文2得到解决。
原因:当判断文件不存在需先创建路径 dFile.mkdir();
个人猜测:Android虚拟机在创建项目后会自动生成/data/data/packagename/databases路径,而真机不可以,所以造成了以上问题。
操作过程:
DBManager.java
public class DBManager {
private static final String DB_NAME = "assistant.db"; //保存的数据库文件名
private static final String PACKAGE_NAME = "com.atlands.assistant";//包名
private static final String DB_PATH = "/data"
+ Environment.getDataDirectory().getAbsolutePath() + "/"
+ PACKAGE_NAME + "/databases"; //存放数据库的位置
private SQLiteDatabase database;
private Context context;
public DBManager(Context context) {
this.context = context;
}
public void openDatabase() {
File dFile = new File(DB_PATH);//判断路径是否存在,不存在则创建路径
if (!dFile.exists()) dFile.mkdir();
this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
}
private SQLiteDatabase openDatabase(String dbfile) {
try {
if (!(new File(dbfile).exists())) {
InputStream is = this.context.getResources().getAssets().open("assistant.db"); //欲导入的数据库
FileOutputStream fos = new FileOutputStream(dbfile);
int BUFFER_SIZE = 1028 * 10;
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
return SQLiteDatabase.openOrCreateDatabase(dbfile,
null);
} catch (FileNotFoundException e) {
Log.e("Database", "File not found");
e.printStackTrace();
} catch (IOException e) {
Log.e("Database", "IO exception");
e.printStackTrace();
}
return null;
}
public void closeDatabase() {
this.database.close();
}
}
MainActivity.java 使用工具类
//导入数据库
dbHelper =new DBManager(this);
dbHelper.openDatabase();
dbHelper.closeDatabase();