簡體   English   中英

如何加快從.txt解析數據並在Android中寫入SQLite的速度?

[英]How to speed up parcing data from .txt and writing to SQLite in Android?

我正在嘗試從.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分鍾。 請為我提供一種盡可能加快速度的方法。

  1. 分析您的代碼,以了解實際花費的時間以及任何更改是否真正有幫助。

  2. 在數據庫事務中包裝數百個插入,以避免等待每個插入上的磁盤I / O。

  3. 使用准備好的SQL語句避免一遍又一遍地重新編譯相同的SQL。

  4. 不要在每次迭代時都將StringBuilder轉換為字符串-僅在循環之后才需要該值。

  5. 可能還有其他一些微優化,例如盡可能避免分配和緩存值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM