开发者

Read text file as resource

I am trying to read a file "words.txt" from a resource. It is a very simple, but large (2 MB), text file that I want to read line by line. I have put the file into /res/raw/words.txt, and try to open it with the following code:

    try 
    {   
        BufferedReader in = 
            new BufferedReader(
            new InputStreamReader(getResources().openRawResource(R.raw.words)));
        String line=in.rea开发者_如何学PythondLine();
        T.append(line); T.append("\n");
        in.close();
    }
    catch (Exception e) { T.append(e.toString()); }

However, I get a java.io.IOException. This is not a "resource not found" exception, so the resource is opened correctly, but the readLine() produces the error.

I tried using the InputStream itself, with the result that read() produces -1, which stands for EOF, as if the file was empty.

Any help for me?


Till now I am still splitting up long files. So this is the best answer I can give. Anyone a better idea?


Try this:

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();
        }


//declare these outside of your load function

public String teststring;
public int loadcounter;

//i put this code in a gl surface load function

//load function //note c changed to context for worky

    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
    }

//I used a file ship1.txt. you need to create a raw folder in your resource folder and then //create a ship1.txt in there. //this code finally solved my simple text load issues

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜