Blog para desarrollo de aplicaciones en Android, aprende paso a paso como crear aplicaciones.

Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación para mostrarle publicidad personalizada y realizar análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. OK Más información | Y más

Cómo Escribir y Leer Archivos de Texto en Android: Tutorial Completo

Cómo Escribir y Leer Archivos de Texto en Android: Tutorial Completo

Aprende paso a paso cómo crear una aplicación Android que pueda guardar y leer archivos de texto usando Java y Android Studio. Este tutorial está diseñado para principiantes que quieren entender la gestión de archivos en Android.


Contenido del Tutorial

  1. Crear un proyecto en Android Studio

  2. Diseño de la aplicación

  3. Código para escribir y leer archivos de texto

  4. Permisos necesarios

  5. Probar la aplicación en un emulador AVD

  6. Preguntas frecuentes (FAQ)


Crear un proyecto en Android Studio

Abre Android Studio y crea un nuevo proyecto con Activity vacío. Para este ejemplo, puedes seguir este enlace de referencia.

Asegúrate de usar Java como lenguaje principal.


Diseño de la aplicación

Vamos a crear un diseño simple que permita al usuario ingresar texto, guardar y leer el contenido de un archivo.

<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <RelativeLayout android:padding="10dp" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/txtInput" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Escribe algo que almacenar" android:gravity="top" /> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/btnSave" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Guardar" android:layout_weight="1" /> <Button android:id="@+id/btnRead" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Leer" android:layout_weight="1" /> </LinearLayout> <TextView android:id="@+id/txtContent" android:layout_width="match_parent" android:layout_height="match_parent" android:inputType="textMultiLine" android:scrollIndicators="bottom|right" android:editable="false" /> </LinearLayout> </RelativeLayout> </androidx.constraintlayout.widget.ConstraintLayout>

Código para escribir y leer archivos de texto

Clase ArchivoHelper

import android.content.Context; import android.os.Environment; import android.util.Log; import java.io.*; public class ArchivoHelper { final static String fileName = "data.txt"; final static String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/instinctcoder/readwrite/"; final static String TAG = ArchivoHelper.class.getName(); // Leer información del archivo public static String ReadFile(Context context){ String line = null; try { FileInputStream fileInputStream = new FileInputStream(new File(path + fileName)); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream)); StringBuilder stringBuilder = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append(System.getProperty("line.separator")); } bufferedReader.close(); fileInputStream.close(); return stringBuilder.toString(); } catch (IOException ex) { Log.d(TAG, ex.getMessage()); return null; } } // Guardar información en el archivo public static boolean saveToFile(String data){ try { new File(path).mkdirs(); File file = new File(path + fileName); if (!file.exists()) file.createNewFile(); FileOutputStream fileOutputStream = new FileOutputStream(file, true); fileOutputStream.write((data + System.getProperty("line.separator")).getBytes()); fileOutputStream.close(); return true; } catch (IOException ex) { Log.d(TAG, ex.getMessage()); return false; } } }

Clase MainActivity

import android.os.Bundle; import android.view.View; import android.widget.*; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button btnRead, btnSave; EditText txtInput; TextView txtContent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtContent = findViewById(R.id.txtContent); txtInput = findViewById(R.id.txtInput); btnRead = findViewById(R.id.btnRead); btnSave = findViewById(R.id.btnSave); btnRead.setOnClickListener(v -> txtContent.setText(ArchivoHelper.ReadFile(MainActivity.this))); btnSave.setOnClickListener(v -> { boolean success = ArchivoHelper.saveToFile(txtInput.getText().toString()); Toast.makeText(MainActivity.this, success ? "Guardado con éxito" : "Error al guardar", Toast.LENGTH_SHORT).show(); }); } }

Permisos necesarios

Agrega este permiso en AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Probar la aplicación en un emulador AVD

Crea un emulador AVD en Android Studio y ejecuta tu proyecto para probar la lectura y escritura de archivos.


🧪 Resultado Final

Tu aplicación mostrará todos los elementos de la siguiente forma. 


📥 Descargar Proyecto de Ejemplo

Puedes descargar el proyecto completo desde el siguiente enlace:

👉 Descargar

🙌 Gracias por visitar mi blog

Si este tutorial  te fue útil:

✔️ Compártelo
✔️ Déjame un comentario
✔️ Sígueme para más contenido sobre Android y programación

¡Estoy aquí para ayudarte!

Preguntas frecuentes (FAQ)

1. ¿Se necesita algún permiso especial para guardar archivos en Android?
Sí, se requiere WRITE_EXTERNAL_STORAGE para guardar archivos en la memoria externa.

2. ¿Puedo usar memoria interna en lugar de externa?
Sí, usando context.openFileInput() y context.openFileOutput(), no necesitas permisos adicionales.

3. ¿Qué pasa si el archivo no existe al leerlo?
El método retornará null. Se recomienda manejar este caso mostrando un mensaje al usuario.

4. ¿Se puede sobrescribir el archivo en lugar de añadir datos?
Sí, cambia new FileOutputStream(file, true) a new FileOutputStream(file, false).

No hay comentarios:

Publicar un comentario