read a text file android

2019-08-20 08:17发布

I am trying to make the computer read a text file full of words and add it to an ArrayList. I made it work on a regular Java application, but can't get it to work on Android. Can someone help me out?

try {
   FileInputStream textfl = (FileInputStream) getAssets().open("test.txt");
   DataInputStream is = new DataInputStream(textfl);
   BufferedReader r = new BufferedReader(new InputStreamReader(is));
    String strLine;

        while ((strLine = r.readLine()) != null) {
            tots.add(strLine);  //tots is the array list
           }  
     } catch (IOException e) {
   // TODO Auto-generated catch block
     e.printStackTrace();
    }

I keep getting a error. The text file is 587kb, so could that be a problem?

1条回答
爷的心禁止访问
2楼-- · 2019-08-20 09:00

try this.

private static String readTextFile(String fileName)
{
    BufferedReader in = null;
    try
    {
        in = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
        String line;
        final StringBuilder buffer = new StringBuilder();
        while ((line = in.readLine()) != null)
        {
            buffer.append(line).append(System.getProperty("line.separator"));
        }
        return buffer.toString();
    }
    catch (final IOException e)
    {
        return "";
    }
    finally
    {
        try
        {
            in.close();
        }
        catch (IOException e)
        {
            // ignore //
        }
    }
}
查看更多
登录 后发表回答