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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With