Skip to content

Instantly share code, notes, and snippets.

@brandhill
Last active January 30, 2023 09:48
Show Gist options
  • Save brandhill/05a0177ddcee3fd44500 to your computer and use it in GitHub Desktop.
Save brandhill/05a0177ddcee3fd44500 to your computer and use it in GitHub Desktop.
Android Read Assets file as string
private String loadAssetTextAsString(Context context, String name) {
BufferedReader in = null;
try {
StringBuilder buf = new StringBuilder();
InputStream is = context.getAssets().open(name);
in = new BufferedReader(new InputStreamReader(is));
String str;
boolean isFirst = true;
while ( (str = in.readLine()) != null ) {
if (isFirst)
isFirst = false;
else
buf.append('\n');
buf.append(str);
}
return buf.toString();
} catch (IOException e) {
Log.e(TAG, "Error opening asset " + name);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e(TAG, "Error closing asset " + name);
}
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment