read a text file android

怎甘沉沦 提交于 2019-12-12 01:31:38

问题


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


来源:https://stackoverflow.com/questions/9676773/read-a-text-file-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!