read a text file android

2019-08-20 08:29发布

问题:

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:

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 //
        }
    }
}