How do I read a text file inside the Assets folder in an Android project?
Ex:
my_project/assets/file.txt
How do I read a text file inside the Assets folder in an Android project?
Ex:
my_project/assets/file.txt
In my case I get an image in assets
More then you change the method according to what you want ....
public Bitmap getAssetFile(Context context, String fileName) {
Bitmap bitmap = null;
Log.i("teste", "getAssetFile: fileName: "+fileName);
try {
File filePath = context.getFileStreamPath(fileName);
bitmap = BitmapFactory.decodeFile(filePath.toString());
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("teste", "getAssetFile: "+e.getMessage());
e.printStackTrace();
}
return bitmap;
}
You can use a method like this:
public static String getFileTextFromAssets(Context context,String[] pFolders, String pFileName)
{
// Stringbuilder que sera utilizado no processamento
StringBuilder sb = new StringBuilder();
// Cria o nome do arquivo a ser carregado
for (String s : pFolders) {
sb.append(s);
sb.append("/");
}
// Adiciona o nome do Arquivo
sb.append(pFileName);
try
{
// Obtem o contexto definido globalmente e abre o arquivo do Assets
InputStream is = context.getAssets().open(sb.toString());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String s = null;
// Instancia do stringbuilder que sera utilizada para leitura do arquivo
sb = new StringBuilder();
while ((s = br.readLine()) != null)
sb.append(s + "\r\n");
br.close();
is.close();
return sb.toString();
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
Considering that inside the Assets folder you can have other folders, just pass an array of String with the path and the second parameter is the name of the file:
String fileText = getFileTextFromAssets(this,new String[] { "" }, "file.txt");