2011-12-16 185 views
6

我必須讀取包含一行字符串的dict.txt文件,並將這些字符串添加到數組列表中。將InputStream讀取到Arraylist

我嘗試這樣做:

public ArrayList<String> myDict = new ArrayList<String>(); 

InputStream is = (getResources().openRawResource(R.raw.dict)); 
BufferedReader r = new BufferedReader(new InputStreamReader(is)); 
try { 
    while (r.readLine() != null) { 
     myDict.add(r.readLine()); 
    } 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

但蹊蹺的...

+0

你第二次閱讀兩次同時添加到列表中。 – 2011-12-16 09:14:24

回答

12

您在每個循環

String line; 
while ((line=r.readLine()) != null) { 
    myDict.add(line); 
} 
+0

你的響應中的「line」變量應該是ArrayList類型的嗎? – Donshon 2015-02-11 19:33:14

8

使用Apache IOUtils迭代兩次:

List<String> lines = IOUtils.readLines(inputStream, "UTF-8"); 
+1

是的!總是指定一個編碼。這是一個很好的習慣。 – Necreaux 2015-04-13 12:03:54