我正在尝试从 .txt 文件中解析数据,然后将其写入数据库。我需要一个单词,并且它是连续的第一个字母。以下是我处理文本文件的方法:
private String convertStreamToString(InputStream is)
throws UnsupportedEncodingException {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
try {
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
allCities = stringBuilder.append(line).toString();
}
} catch (IOException e) {
Log.e("error", e.getMessage());
}
return allCities;
}
private String getAllWordsString() throws IOException {
AssetManager am = context.getAssets();
InputStream is = am.open(Constants.FILE_NAME);
allWords = convertStreamToString(is);
is.close();
return allWords;
}
这是我将其写入数据库的方法:
public void inputDBFeed(MyWord model) {
ContentValues cv = new ContentValues();
cv.put(Constants.COLUMN_NAME, model.getName());
cv.put(Constants.COLUMN_FIRST_LETTER, model.getFirstLetter());
database.insert(Constants.MAIN_DB_NAME, null, cv);
}
public void prepareDBFeed() {
try {
allWords = this.getAllWordsString();
} catch (IOException e) {
Log.e("Error:", e.getMessage());
}
String[] cities = allWords.split(" ");
for (String oneWord : words) {
App.getDBManager().inputDBFeed(new Word(oneWord, getFirstLetter(oneWord)));
}
}
但在设备上运行此过程需要 2 到 5 分钟。请给我一种尽可能加快速度的方法。
最佳答案
分析您的代码,看看时间真正花在哪里以及任何更改是否真正有帮助。
将数百个插入包含在一个数据库事务中,以避免每次插入时等待磁盘 I/O。
使用准备好的 SQL 语句以避免一遍又一遍地重新编译相同的 SQL。
不要在每次迭代时将
StringBuilder
转换为字符串 - 您仅在循环之后需要该值。可能还有其他一些微观优化,例如尽可能避免分配和缓存值。
关于java - 如何在 Android 中加速从 .txt 解析数据并写入 SQLite?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23313520/