116

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

InputStream inputStream = openFileInput("test.txt");
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

我的问题是:我应该把这个"test.txt"文件放在我的项目中的什么地方?我曾尝试将文件放在文件夹下"res/raw""asset"但我得到了exception "FileNotFound"上面编写的代码的第一次运行时间。

4

7 回答 7

183

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

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

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

InputStream is = context.getResources().openRawResource(R.raw.test);
于 2011-04-24T15:19:58.797 回答
26

试试这个,

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();
    }
}
于 2011-04-25T04:04:14.303 回答
23

我就是这样做的:

public static String readFromAssets(Context context, String filename) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));

    // do reading, usually loop until end of file reading  
    StringBuilder sb = new StringBuilder();
    String mLine = reader.readLine();
    while (mLine != null) {
        sb.append(mLine); // process line
        mLine = reader.readLine();
    }
    reader.close();
    return sb.toString();
}

按如下方式使用它:

readFromAssets(context,"test.txt")
于 2016-01-17T09:44:55.357 回答
7

在您的assets文件夹中有一个文件需要您使用这段代码才能从assets文件夹中获取文件:

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

在此示例中,getAssets()返回一个AssetManager实例,然后您可以自由地使用AssetManagerAPI 中的任何方法。

于 2011-04-24T15:21:30.433 回答
5

在 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); }
于 2013-07-03T03:33:33.387 回答
3

读取保存在 assets 文件夹中的文件

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 "" ;
        }
    }
于 2016-06-01T12:29:40.267 回答
0

raw这是一个处理和asset文件的简单类:

公共类 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");
于 2018-04-06T10:19:21.330 回答