How to read a text file from "assets" directory as a string?

Mascarpone picture Mascarpone · Feb 1, 2011 · Viewed 32.1k times · Source

I have a file in my assets folder... how do I read it?

Now I'm trying:

      public static String readFileAsString(String filePath)
        throws java.io.IOException{
            StringBuffer fileData = new StringBuffer(1000);
            BufferedReader reader = new BufferedReader(
                    new FileReader(filePath));
            char[] buf = new char[1024];
            int numRead=0;
            while((numRead=reader.read(buf)) != -1){
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
                buf = new char[1024];
            }
            reader.close();
            return fileData.toString();
        }

But it cast a null pointer exception...

the file is called "origin" and it is in folder assets

I tried to cast it with:

readFileAsString("file:///android_asset/origin");

and

readFileAsString("asset/origin");``

but both failed... any advice?

Answer

Raceimaztion picture Raceimaztion · Feb 1, 2011

BufferedReader's readLine() method returns a null when the end of the file is reached, so you'll need to watch for it and avoid trying to append it to your string.

The following code should be easy enough:

public static String readFileAsString(String filePath) throws java.io.IOException
{
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    String line, results = "";
    while( ( line = reader.readLine() ) != null)
    {
        results += line;
    }
    reader.close();
    return results;
}

Simple and to-the-point.