martes, 8 de noviembre de 2011

Manejo de Ficheros

Los ficheros los meteremos en el directorio assets
Para tener acceso a los ficheros que hemos metido aquí usaremos la clase AssetManager.
  AssetManager assetManager = context.getAssets();
El interfaz Context esta implementado por la clase Activity asi que lo llamaremos desde ella.

InputStream inputStream = assetManager.open(
"dir1/dir2/nombrefichero.txt");
Este método devuelve un InputStream.
Ejemplo:
public class PruebaAssets extends Activity
{
    @Override public void onCreate(Bundle savedInstanceState)
    {
            super.onCreate(savedInstanceState);
            TextView textView = new TextView(this);
            setContentView(textView);
            AssetManager assetGestor = getAssets();
            InputStream inputStream = null;
            try
            {
                inputStream = assetGestor.open("textos/mifichero.txt");
                String text = loadTextFile(inputStream);
                textView.setText(text);
            }
            catch (IOException e)
            {
                textView.setText("Couldn't load file");
            }
            finally
            {
                if (inputStream != null)
                try
                {
                    inputStream.close();
                }
                catch (IOException e)
                {
                    textView.setText("Couldn't close file");
                }
            }
    }

}

No hay comentarios:

Publicar un comentario