Read file in the Assets folder

1

How do I read a text file inside the Assets folder in an Android project?

Ex:

my_project/assets/file.txt
    
asked by anonymous 12.07.2014 / 04:58

2 answers

1

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;
}
    
12.07.2014 / 16:36
2

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");
    
12.07.2014 / 09:29