Android将文本文件(.txt)读入字符串数组

时间:2013-10-20 12:28:53

标签: java android arrays error-handling text-files

这是代码:

 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:我搜索过并找到了其他类似的问题和答案,但这对我没有帮助......

2 个答案:

答案 0 :(得分:0)

更改此

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

到这个

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

答案 1 :(得分:0)

试试这个:

    void CreateWordList()throws IOException{
...}