Read file in Assets folder

Asked

Viewed 2,277 times

1

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

Ex:

my_project/assets/file.txt

2 answers

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);
    }

}

Whereas within the Assets folder you can have other folders, just pass a String array with the path and the second parameter is the file name:

String fileText = getFileTextFromAssets(this,new String[] { "" }, "file.txt");
  • In the getFileTextFromAssets statement you have three parameters, however in the method call you pass only two arguments. Another thing, we missed the "t" in "getFileTextFromAsses". Other than that, your answer is correct.

  • Yes, because I’ve done on hand now rsrsrs, but you’re right. I’ll fix.

1


in my case I get an image on the Assets

the more 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.