Here is a simple class that handles both raw
and asset
files :
public class ReadFromFile {
public static String raw(Context context, @RawRes int id) {
InputStream is = context.getResources().openRawResource(id);
int size = 0;
try {
size = is.available();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return readFile(size, is);
}
public static String asset(Context context, String fileName) {
InputStream is = null;
int size = 0;
try {
is = context.getAssets().open(fileName);
AssetFileDescriptor fd = null;
fd = context.getAssets().openFd(fileName);
size = (int) fd.getLength();
fd.close();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return readFile(size, is);
}
private static String readFile(int size, InputStream is) {
try {
byte buffer[] = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
For example :
ReadFromFile.raw(context, R.raw.textfile);
And for asset files :
ReadFromFile.asset(context, "file.txt");