¿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?
- Cómo guardar el archivo descargado en la tarjeta sd del gestor de descargas mediante programación en android
- Cómo crear el directorio de Android automáticamente si aún no existe
- Android - No se puede cargar el archivo gif usando la clase Movie
- Abra todas las imágenes de una carpeta (tarjeta SD) al mismo tiempo, haga clic en el botón
- Advertencia: File.mkdir () se ignora
- Cómo hacer un archivo oculto en la tarjeta android sd?
- El desplazamiento de la aplicación de Android a la opción sdcard es deshabilitado
- Donde el listview almacena la imagen en android cuando se descarga desde el servidor
- Todavía el permiso denegado después de agregar "WRITE_EXTERNAL_STORAGE" en AndroidManifest.xml
- ¿Cómo obtener el Uri de una imagen almacenada en el SDCARD?
- ¿Tengo que declarar WRITE_EXTERNAL_STORAGE y READ_EXTERNAL_STORAGE?
- ¿Cómo puedo transferir una imagen de su URL a la tarjeta SD?
- Movimiento de Android al comportamiento de la tarjeta SD
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 }
- La vista de reciclaje dentro de NestedScrollView hace que el desplazamiento comience en el centro
- Regresando de una actividad usando navigateUpFromSameTask ()