¿Cómo puedo leer un archivo de texto desde la tarjeta SD en Android?

Soy nuevo en el desarrollo de Android.

Necesito leer un archivo de texto de la tarjeta SD y mostrar ese archivo de texto. ¿Hay alguna manera de ver un archivo de texto directamente en Android o bien ¿cómo puedo leer y mostrar el contenido de un archivo de texto?

En tu diseño necesitarás algo para mostrar el texto. Un TextView es la elección obvia. Así que tendrás algo como esto:

 <TextView android:id="@+id/text_view" android:layout_width="fill_parent" android:layout_height="fill_parent"/> 

Y su código se verá así:

 //Find the directory for the SD Card using the API //*Don't* hardcode "/sdcard" File sdcard = Environment.getExternalStorageDirectory(); //Get the text file File file = new File(sdcard,"file.txt"); //Read text from file StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } br.close(); } catch (IOException e) { //You'll need to add proper error handling here } //Find the view by its id TextView tv = (TextView)findViewById(R.id.text_view); //Set the text tv.setText(text); 

Esto podría ir en el método onCreate() de su Activity , o en algún otro lugar dependiendo de lo que es lo que quieres hacer.

En respuesta a

No digas hardcode / sdcard /

A veces TENEMOS que codificarlo como en algunos modelos de teléfono el método API devuelve la memoria interna del teléfono.

Tipos conocidos: HTC One X y Samsung S3.

Environment.getExternalStorageDirectory (). GetAbsolutePath () da una ruta diferente – Android

 package com.example.readfilefromexternalresource; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.os.Bundle; import android.os.Environment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import android.os.Build; public class MainActivity extends Activity { private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView)findViewById(R.id.textView); String state = Environment.getExternalStorageState(); if (!(state.equals(Environment.MEDIA_MOUNTED))) { Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show(); } else { BufferedReader reader = null; try { Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG).show(); File file = Environment.getExternalStorageDirectory(); File textFile = new File(file.getAbsolutePath()+File.separator + "chapter.xml"); reader = new BufferedReader(new FileReader(textFile)); StringBuilder textBuilder = new StringBuilder(); String line; while((line = reader.readLine()) != null) { textBuilder.append(line); textBuilder.append("\n"); } textView.setText(textBuilder); } catch (FileNotFoundException e) { // TODO: handle exception e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if(reader != null){ try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } 
 BufferedReader br = null; try { String fpath = Environment.getExternalStorageDirectory() + <your file name>; try { br = new BufferedReader(new FileReader(fpath)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } String line = ""; while ((line = br.readLine()) != null) { //Do something here } 
  • Simple mediaplayer reproducir mp3 desde la ruta del archivo?
  • Error que abre el archivo del rastro: Ningún archivo o directorio (2)
  • Problema que empuja archivo grande a Emulator / SDcard con Eclipse DDMS
  • ¿Cómo acceder al almacenamiento extraíble en dispositivos Android?
  • Cómo reproducir archivos mp3 de la tarjeta SD interna y externa en android?
  • Android obtiene tamaño libre de memoria interna / externa
  • Android: quitar una imagen de la tarjeta sd
  • Archivo de documentos de Android 5.0 desde el árbol URI
  • Directorio de almacenamiento de Android Open External Storage (sdcard) para almacenar el archivo
  • Almacenamiento externo de Android entre las marcas para móviles
  • ¿Cómo obtener acceso a todas las tarjetas SD, utilizando la nueva Lollipop API?
  • Interesting Posts
    FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.