如果数据库不存在,我想将数据库从 txt 写入数据库:
File database=getApplicationContext().getDatabasePath("commments.db");
if (!database.exists()) {
// Database does not exist so copy it from assets here
try {
txtToDb();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("Database", "Not Found");
} else {
Log.i("Database", "Found");
}
它不起作用,数据库一次又一次地被填满。我究竟做错了什么?
更新:txtToDb():
public void txtToDb () throws IOException {
InputStream is =getResources().openRawResource(R.raw.data);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
byte[] myData = baf.toByteArray();
String dataInString = new String(myData);
String[] lines = dataInString.split("\n");
for (int i=0; i<lines.length; i++){
comment = datasource.createComment(lines[i]);
// adapter.add(comment);
}
writeDbToSd();
}
DbToSd() 将 DB 写入 SDCARD,以便我可以使用 adb pull 来查看它。这两个功能都可以自己正常工作。createComment 在另一个函数中将解析的字符串添加到数据库。