读取文本文件android

时间:2012-03-13 00:32:11

标签: android text-files fileinputstream datainputstream

我试图让计算机读取一个充满单词的文本文件并将其添加到ArrayList中。我使它在常规Java应用程序上运行,但无法让它在Android上运行。有人可以帮助我吗?

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

我一直收到错误。文本文件是587kb,那么这可能是个问题吗?

1 个答案:

答案 0 :(得分:1)

试试这个。

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