2012-03-13 89 views
0

我想讓計算機讀取一個文本文件充滿單詞並將其添加到一個ArrayList。我使它在一個普通的Java應用程序上工作,但無法讓它在Android上運行。有人可以幫我嗎?閱讀一個文本文件android

try { 
    FileInputStream textfl = (FileInputStream) getAssets().open("test.txt"); 
    DataInputStream is = new DataInputStream(textfl); 
    BufferedReader r = new BufferedReader(new InputStreamReader(is)); 
    String strLine; 

     while ((strLine = r.readLine()) != null) { 
      tots.add(strLine); //tots is the array list 
      } 
    } catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } 

我不斷收到錯誤。該文本文件是587kb,這可能是一個問題?

+0

你會得到什麼錯誤?編輯你的問題,包括這個! – Argyle 2012-03-13 00:46:40

+0

你想如何顯示它?在ListView中,每個項目都是可點擊的?或者在一個TextView中? – FoamyGuy 2012-03-13 00:54:02

+0

我只是想將它添加到數組列表,然後從那裏它將被添加到列表中的文本視圖。它說38行錯誤是FileInputStream textfl =(FileInputStream)getAssets()。open(「test.txt」); 03-13 00:22:02.150:E/AndroidRuntime(480):\t at steve.fina.androidsm.FinalActivity.onCreate(FinalActivity.java:38) -thx btw的響應 – 2012-03-13 00:59:25

回答

1

試試這個。

private static String readTextFile(String fileName) 
{ 
    BufferedReader in = null; 
    try 
    { 
     in = new BufferedReader(new InputStreamReader(getAssets().open(fileName))); 
     String line; 
     final StringBuilder buffer = new StringBuilder(); 
     while ((line = in.readLine()) != null) 
     { 
      buffer.append(line).append(System.getProperty("line.separator")); 
     } 
     return buffer.toString(); 
    } 
    catch (final IOException e) 
    { 
     return ""; 
    } 
    finally 
    { 
     try 
     { 
      in.close(); 
     } 
     catch (IOException e) 
     { 
      // ignore // 
     } 
    } 
} 
+0

我應該在哪裏找到txt文件? – WardaLyn 2014-06-05 06:43:31

+0

在Android應用程序的資產文件夾中 – 2014-06-05 07:26:47