读取一个简单的文本文件

118

我正在尝试在我的示例Android应用程序中读取一个简单的文本文件。我正在使用下面的代码来读取这个简单的文本文件。

InputStream inputStream = openFileInput("test.txt");
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
我的问题是:我应该把这个 "test.txt" 文件放在我的项目的哪里?我尝试将文件放在 "res/raw" 和 "asset" 文件夹下,但当上面的代码第一次执行时,我会收到 "FileNotFound" 异常。
6个回答

183

将您的文本文件放在Android项目下的/assets目录中。使用AssetManager类来访问它。

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

或者您也可以将文件放入/res/raw目录中,在该目录下的文件将被索引,并且可以通过R文件中的ID访问:

InputStream is = context.getResources().openRawResource(R.raw.test);

9
我在想这两种方法之间的性能差异,但快速基准测试显示没有显著差异。 - Reuben L.
2
我的“hello world”应用程序中没有“asset”文件夹。我需要手动创建吗? - Kaushik Lele
@ReubenL。一个区别在于/assets 文件夹中的文件大小不能超过1 Mb,而/res/raw 文件夹中的文件大小可以超过1 Mb。来源:https://dev59.com/WlLTa4cB1Zd3GeqPcJ9J - Tutompita
4
顺便提一下,自Android Studio 1.2.2版本起,必须手动添加 /assets 目录。它应该放在 src/main 目录下。 - Jpaji Rajnish
3
像@KaushikLele这样想知道如何获取上下文的人,很容易。在一个活动中,你可以通过使用“this”关键字或调用“getCurrentContext()”方法来获取它。 - Alex
显示剩余4条评论

25

试试这个,

package example.txtRead;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class txtRead extends Activity {
    String labels="caption";
    String text="";
    String[] s;
    private Vector<String> wordss;
    int j=0;
    private StringTokenizer tokenizer;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        wordss = new Vector<String>();
        TextView helloTxt = (TextView)findViewById(R.id.hellotxt);
        helloTxt.setText(readTxt());
 }

    private String readTxt(){

     InputStream inputStream = getResources().openRawResource(R.raw.toc);
//     InputStream inputStream = getResources().openRawResource(R.raw.internals);
     System.out.println(inputStream);
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

     int i;
  try {
   i = inputStream.read();
   while (i != -1)
      {
       byteArrayOutputStream.write(i);
       i = inputStream.read();
      }
      inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

     return byteArrayOutputStream.toString();
    }
}

7

如果您的文件在assets文件夹中,则需要使用以下代码从assets文件夹获取文件:

yourContext.getAssets().open("test.txt");

在这个例子中,getAssets() 返回一个 AssetManager 实例,然后你可以自由地使用 AssetManager API 中的任何方法。

5

在 Mono For Android 中...

try
{
    System.IO.Stream StrIn = this.Assets.Open("MyMessage.txt");
    string Content = string.Empty;
    using (System.IO.StreamReader StrRead = new System.IO.StreamReader(StrIn))
    {
      try
      {
            Content = StrRead.ReadToEnd();
            StrRead.Close();
      }  
      catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
      }
          StrIn.Close();
          StrIn = null;
}
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }

3

读取保存在资产文件夹中的文件

public static String readFromFile(Context context, String file) {
        try {
            InputStream is = context.getAssets().open(file);
            int size = is.available();
            byte buffer[] = new byte[size];
            is.read(buffer);
            is.close();
            return new String(buffer);
        } catch (Exception e) {
            e.printStackTrace();
            return "" ;
        }
    }

1
"is.available();" 不安全。请使用 "AssetFileDescriptor fd = getAssets().openFd(fileName); int size = (int) fd.getLength(); fd.close();" - GBY

0
这是一个处理rawasset文件的简单类:

public class ReadFromFile {

public static String raw(Context context, @RawRes int id) {
    InputStream is = context.getResources().openRawResource(id);
    int size = 0;
    try {
        size = is.available();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    return readFile(size, is);
}

public static String asset(Context context, String fileName) {
    InputStream is = null;
    int size = 0;
    try {
        is = context.getAssets().open(fileName);
        AssetFileDescriptor fd = null;
        fd = context.getAssets().openFd(fileName);
        size = (int) fd.getLength();
        fd.close();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    return readFile(size, is);
}


private static String readFile(int size, InputStream is) {
    try {
        byte buffer[] = new byte[size];
        is.read(buffer);
        is.close();
        return new String(buffer);
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}

}

例如:
ReadFromFile.raw(context, R.raw.textfile);

至于资源文件:

ReadFromFile.asset(context, "file.txt");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接