
Grabar un fichero en almacenamiento externo
Publicado por Miguel Angel (5 intervenciones) el 16/12/2016 07:46:48
Hola, quiero grabar un fichero en el almacenamiento interno, para que después el usuario si quiere pueda enviarlo por Email o descargarlo a su pc, etc.
En el fichero AndroidManifiest.xml, tengo otorgado el permiso con la línea:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Y el código que uso para guardar el fichero es el siguiente:
El error me lo da en la siguiente línea:
OutputStreamWriter archivo= new OutputStreamWriter(new FileOutputStream(nomFichero));
Al llegar aquí salta al catch y me muestra el error que pongo en el toast.
Alguna sugerencia?
Gracias.
En el fichero AndroidManifiest.xml, tengo otorgado el permiso con la línea:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Y el código que uso para guardar el fichero es el siguiente:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public void copiaSeguridad(View v) {
try {
//Creamos un objeto para obtener la ruta de la tarjeta SD
File tarjeta = Environment.getExternalStorageDirectory(;
Toast.makeText(this,tarjeta.getPath().toString(),Toast.LENGTH_SHORT).show();
//Creamos un objeto File indicandole el camino de la unidad SD y el nombre del fichero
File nomFichero = new File(tarjeta.getAbsolutePath(), "pepito.txt");
//Creamos el objeto OutputStreamWriter para poder grabar en el fichero
OutputStreamWriter archivo= new OutputStreamWriter(new FileOutputStream(nomFichero));
//Conectamos con la base de datos
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "administracion", null, 1);
SQLiteDatabase bd = admin.getWritableDatabase();
String linea="";
//Realizamos la consulta
Cursor fila = bd.rawQuery("select * from cuentas order by aplicacion", null);
//Recorremos la tabla hasta el final
while (fila.moveToNext()) {
String aplicacion=fila.getString(0);
String usuario=fila.getString(1);
String clave=fila.getString(2);
aplicacion=espacios(aplicacion);
usuario=espacios(usuario);
clave=espacios(clave);
linea = aplicacion + usuario + clave + "\n";
archivo.write(linea);
Toast.makeText(this, "Linea añadida: " + linea,Toast.LENGTH_SHORT).show();
}
bd.close(); //Cerramos la base de datos
archivo.flush(); //Vuelca los datos que queden el buffer al archivo
archivo.close(); //Cerramos el archivo
Toast.makeText(this, "Copia realizada",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Error al abrir el fichero",Toast.LENGTH_SHORT).show();
} // fin try
} //copiaSeguridad
El error me lo da en la siguiente línea:
OutputStreamWriter archivo= new OutputStreamWriter(new FileOutputStream(nomFichero));
Al llegar aquí salta al catch y me muestra el error que pongo en el toast.
Alguna sugerencia?
Gracias.
Valora esta pregunta


0