简体   繁体   English

读取一个文本文件android

[英]read a text file android

I am trying to make the computer read a text file full of words and add it to an ArrayList. 我试图使计算机读取一个充满单词的文本文件,并将其添加到ArrayList中。 I made it work on a regular Java application, but can't get it to work on Android. 我使它可以在常规Java应用程序上运行,但无法使其在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? 文本文件为587kb,所以这可能是个问题吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM