2013-02-28 95 views
1

我正在從文本文件中讀取單詞的字典應用程序,但文本文件的大小爲10mb,因此無法在模擬器或設備上運行它由於內存限制。在Android應用程序中讀取大型10mb文本文件

那麼這個問題的解決方案是什麼?我可以在壓縮文件時從壓縮文件讀取文本文件,還是將它分成10個獨立的文本文件(每個文件文件爲1mb)會更好?

下面是當前閱讀文本文件的代碼,我必須對代碼做些什麼改變?

private synchronized void loadWords(Resources resources) throws IOException { 
     if (mLoaded) return; 

     Log.d("dict", "loading words"); 
     InputStream inputStream = resources.openRawResource(R.raw.definitions); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 

     try { 
      String line; 
      while((line = reader.readLine()) != null) { 
       String[] strings = TextUtils.split(line, ":"); 
       if (strings.length < 2) continue; 
       addWord(strings[0].trim(), strings[1].trim()); 
      } 
     } finally { 
      reader.close(); 
     } 
     mLoaded = true; 
    } 

public synchronized List<Word> getAllMatches(Resources resources) throws IOException { 
     List<Word> list = new ArrayList<Word>(); 
     InputStream inputStream = resources.openRawResource(R.raw.definitions); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 

     try { 
      String line; 
      while((line = reader.readLine()) != null) { 
       String[] strings = TextUtils.split(line, ":"); 
       if (strings.length < 2) continue; 
       Word word = new Word(strings[0].trim(), strings[1].trim()); 
       list.add(word); 
      } 
     } finally { 
      reader.close(); 
     } 

     return list; 
    } 
+1

不確定它是否可以更有效,但10mb只是很大。在字典中,按照首字母來分割它並不奇怪。 – 2013-02-28 11:43:54

+1

@OlympicBeast是否有任何理由不使用SQLite數據庫? – fardjad 2013-02-28 11:47:14

+0

@fardjad我以前從未在我的應用中使用SQLite數據庫,所以我想我會使用該文本文件,因爲稍後可以更容易地進行編輯。 – DevCon 2013-02-28 11:51:47

回答

0

人們可以使用的gzip單個文件壓縮( 「大text.txt.gz」),並使用GZipInputStream。

相同的字符串應該在內存中保留一次。在需要時,通過一個字符串之前,你可以搜索一下:

Map<String, String> sharedStrings = new HashMap<>(); 

String share(String s) { 
    String sToo = sharedStrings.get(s); 
    if (sToo == null) { 
     sToo = s; 
     sharedStrings.put(s, s); 
    } 
    return sToo; 
} 

使用數據庫的建議是一個很好的了。

相關問題