【问题标题】:Android reading text files(.txt) into an array of stringsAndroid 将文本文件(.txt)读入字符串数组
【发布时间】:2013-10-20 12:28:53
【问题描述】:

这是代码:

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

【问题讨论】:

  • lines.readLine() 不会在文件结束时返回 null,它会返回 -1
  • 困惑 - 我在你的代码中看不到一个 try/catch。我怀疑编译。请发布您的真实代码。
  • 抱歉后我添加了 try/catch,我将编辑问题
  • 现在我编辑了代码并添加了 try/catch

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


【解决方案1】:

改变这个

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

到这里

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

【讨论】:

    【解决方案2】:

    试试这个:

        void CreateWordList()throws IOException{
    ...}
    

    【讨论】:

      猜你喜欢
      • 2017-09-12
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多