阅读一个简单的文本文件

时间:2012-12-24 17:47:11

标签: android

大家好我试图从android中的文件中读取日期。我正在使用Eclipse,程序正在编译和运行,只是它没有打印txt文件的上下文。这是我的加载方法

    private String load(String filename) {
        try {
//          Log.v("Home", " in the load method");
            Log.d("Home", " in the load method");

            final FileInputStream fis = openFileInput(filename);
//          final InputStream fis =  getResources().openRawResource(R.raw.pages);

            final BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            fis.close();
            return sb.toString();
        } catch (Exception ex) {
            return "No entry exists for this file";
        }
    }

在oncreate中我只是访问它

String fileName = "pages.txt";
load(fileName);

pages.txt位于res / raw目录中。我试图用两个

读取文件
final FileInputStream fis = openFileInput(filename);
// final InputStream fis =  getResources().openRawResource(R.raw.pages);

但它没有打印上下文。

我在onCreate方法中添加了

Log.d("File", load(fileName));

但是返回了catch语句No entry exists for this file.

由于

1 个答案:

答案 0 :(得分:0)

尝试使用如下,

System.out.println(load(raw.pages));



 private String load(int id) {
        try {           
             Resources res = getResources();
             InputStream fis = res.openRawResource(id);
            final BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            fis.close();
            return sb.toString();
        } catch (Exception ex) {
            return "No entry exists for this file";
        }
    }