2011-12-16 47 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