简体   繁体   English

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

[英]Android reading text files(.txt) into an array of strings

This is the code: 这是代码:

 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();
        }
}

I have a error at " line = lines.readLine(); " that says "Unhandled exception of type IOException" so i surrounded it with try/catch. 我在“ line = lines.readLine(); ”时line = lines.readLine(); 错误 ,提示“ IOException类型的未处理异常”,所以我用try / catch包围了它。

And I have another error at " BufferedReader lines = new BufferedReader(new InputStreamReader(is, "UTF-8")); " that says "Unhandled exception type UnsupportedEncodingException" so i surrounded it with try/catch. 而且我在“ BufferedReader lines = new BufferedReader(new InputStreamReader(is, "UTF-8")); “处BufferedReader lines = new BufferedReader(new InputStreamReader(is, "UTF-8"));另一个错误 ,该错误 BufferedReader lines = new BufferedReader(new InputStreamReader(is, "UTF-8")); “未处理的异常类型UnsupportedEncodingException”,所以我用try / catch包围了它。

Now when i run the app it crashes... 现在,当我运行该应用程序时,它崩溃了...

What am I doing wrong ? 我究竟做错了什么 ?

How can I read a text file and add each line to an array of strings ? 如何读取文本文件并将每一行添加到字符串数组?

PS: I have searched and found other similar questions and answers but that did not help me... PS:我搜索并找到了其他类似的问题和答案,但这并没有帮助我...

change this 改变这个

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

to this 对此

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

Try this: 尝试这个:

    void CreateWordList()throws IOException{
...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM