Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 994
Mascarpone Avatar asked Feb 01 '11 18:02

Mascarpone


1 Answers

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.

like image 99
Raceimaztion Avatar answered Sep 22 '22 13:09

Raceimaztion