阅读一个简单的文本文件

时间:2011-04-24 15:18:49

标签: android text-files java-io

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

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

我的问题是: 我应该将这个"test.txt"文件放在我的项目中?我已经尝试将该文件放在"res/raw""asset"文件夹下,但是当上面编写的代码第一次执行时,我得到了exception "FileNotFound"

感谢您的帮助

7 个答案:

答案 0 :(得分:180)

将您的文本文件放在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);

答案 1 :(得分: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();
    }
}

答案 2 :(得分: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")

答案 3 :(得分:7)

assets文件夹中包含文件需要您使用这段代码才能从assets文件夹中获取文件:

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

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

答案 4 :(得分: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); }

答案 5 :(得分: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 "" ;
        }
    }

答案 6 :(得分:0)

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

公共类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");