1

I am new in android development, and I'm trying to create a simple application which reads some data from a text file and displays it in a ListView. The problem is my reader doesn't find my file. I've debugged my application and that is the conclusion I've come up with. So, where does the text file have to placed in order for the reader to find it? Heres some code:

     try
    {
          FileInputStream fstream = new FileInputStream("movies.txt");
          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));

          String strLine;

          while ((strLine = br.readLine()) != null)
          {
              filme.add(strLine);
              Log.d(LOG_TAG,"movie name:" + strLine);
          }
          in.close();
    }
    catch (Exception e)
    {
                System.err.println("Error: " + e.getMessage());
    }

Thanks!

4

4 回答 4

1

将名为movies.txt的文件放在res/raw中,然后使用如下代码

String displayText = "";
try {
InputStream fileStream = getResources().openRawResource(
                    R.raw.movies);
int fileLen = fileStream.available();
// Read the entire resource into a local byte buffer.
byte[] fileBuffer = new byte[fileLen];
fileStream.read(fileBuffer);
fileStream.close();
displayText = new String(fileBuffer);
} catch (IOException e) {
  // exception handling
}
于 2012-08-29T06:59:42.547 回答
0

通常,当您要打开一个文件时,您会将其放入项目的 res 文件夹中。当你想打开一个文本文件时,你可以把它放到 res/raw 目录下。您的 Android eclipse 插件将为您生成一个包含文本文件句柄的资源类。

要访问您的文件,您可以在活动中使用它:

InputStream ins = getResources().openRawResource(R.raw.movies);

其中“movies”是不带文件类型的文件名。

于 2012-08-29T07:06:48.040 回答
0
FileInputStream fstream = new FileInputStream("movies.txt");

movies.txt 的路径在哪里?您必须将路径指定为 sd 卡或内部存储,无论您存储在哪里。

好像在sd卡里

 FileInputStream fstream = new FileInputStream("/sdcard/movies.txt");
于 2012-08-29T07:01:05.567 回答
0

如果您将文件存储在 SD 卡上,那么您可以使用Environment.getExternalStorageDirectory().

请注意,例如,如果 SD 卡已安装到计算机上,您可能无法访问它。

您可以像这样检查外部存储的状态:

boolean externalStorageAvailable = false;
boolean externalStorageWriteable = false;    

String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
    externalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    externalStorageAvailable = true;
    externalStorageWriteable = false;
} else {
    externalStorageAvailable = mExternalStorageWriteable = false;
}

if(externalStorageAvailable && externalStorageWriteable){
    File sdRoot = Environment.getExternalStorageDirectory();
    File myFile = new File(sdRoot, "path/to/my/file.txt");
}
于 2012-08-29T07:34:12.300 回答