读取文本文件作为资源

时间:2010-09-14 08:36:30

标签: android

我正在尝试从资源中读取文件“words.txt”。这是一个非常简单但很大(2 MB)的文本文件,我想逐行阅读。我已将文件放入/res/raw/words.txt,并尝试使用以下代码打开它:

    try 
    {   
        BufferedReader in = 
            new BufferedReader(
            new InputStreamReader(getResources().openRawResource(R.raw.words)));
        String line=in.readLine();
        T.append(line); T.append("\n");
        in.close();
    }
    catch (Exception e) { T.append(e.toString()); }

但是,我得到了一个java.io.IOException。这不是“未找到资源”异常,因此资源正确打开,但readLine()会产生错误。

我尝试使用InputStream本身,结果是read()产生-1,代表EOF,就像文件是空的一样。

对我有任何帮助吗?


直到现在我仍在拆分长文件。所以这是我能给出的最佳答案。谁有更好的主意?

2 个答案:

答案 0 :(得分:3)

试试这个:

InputStream is = c.getResources().openRawResource(R.raw.csv_file);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String readLine = null;

        try {
            while ((readLine = br.readLine()) != null) {


            }
        } catch (IOException e) {
            e.printStackTrace();
        }

答案 1 :(得分:0)

//在你的加载函数之外声明这些

public String teststring;
public int loadcounter;

//我把这段代码放在gl表面加载函数

//加载功能 //注意c改为上下文

    InputStream is = context.getResources().openRawResource(R.raw.ship1);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String readLine = null;

    try {
        while ((readLine = br.readLine()) != null) {

            if(loadcounter ==0)
            {
                teststring=br.readLine();//get first line to printable string   
                    //this code works
                  //array[loadcounter] = br.readLine();
              //want to get this remarked part working for level load
                 }
         loadcounter++; //var will increment an array
        }

    } catch (IOException e) {
        e.printStackTrace(); //create exception output
    }

//我使用了一个文件ship1.txt。你需要在资源文件夹中创建一个原始文件夹,然后//在那里创建一个ship1.txt。  //这段代码最终解决了我的简单文本加载问题

相关问题