2013-10-20 78 views
0

此數組是代碼:的Android閱讀文本文件(.txt)轉換成字符串

void CreateWordList() 
{ 
    Toast.makeText(getBaseContext(), "Creating Word List...", Toast.LENGTH_SHORT).show(); 
    InputStream is = getResources().openRawResource(R.raw.pass); 
    BufferedReader lines = null; 
    try { 
     lines = new BufferedReader(new InputStreamReader(is, "UTF-8")); 
    } catch (UnsupportedEncodingException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
    ArrayList<String> list = new ArrayList<String>(); 
    String line = null; 
     try { 
      while((line = lines.readLine()) !=null)list.add(line); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
      wordlist = (String[]) list.toArray(); 
     if (wordlist[1] == null) 
     { 
      Toast.makeText(getBaseContext(), "ERROR: Word List = null", Toast.LENGTH_SHORT).show(); 
     } 
} 

我在「line = lines.readLine();」,上面寫着「型IOException的未處理的異常」,所以我周圍有一個錯誤它與try/catch。

而且我還有一個錯誤在「BufferedReader lines = new BufferedReader(new InputStreamReader(is, "UTF-8"));」,上面寫着「未處理的異常類型UnsupportedEncodingException」,所以我用的try/catch包圍它。

現在,當我運行應用程序崩潰...

我在做什麼錯了?

如何讀取文本文件並將每行添加到字符串數組?

PS:我已經搜查,發現其他類似的問題和答案,但沒有幫助我...

+0

lines.readLine()不會返回null,如果文件完成,它會返回-1 –

+0

混淆 - 我看不到你的代碼中有一個try/catch。我懷疑編譯。請發佈您的真實代碼。 –

+0

我加了try/catch對不起,我會編輯問題 – user2635745

回答

0

改變這種

while(true){ 
line = lines.readLine(); 

這個

while((line = lines.readLine()) !=null) 
+0

我得到了同樣的結果... – user2635745

0

試試這個:

void CreateWordList()throws IOException{ 
...} 
+0

And ...他爲什麼要這樣做? –