2010-08-23 18 views
76

estoy usando el siguiente código para descargar un archivo de mi servidor a continuación, escribir al directorio raíz de la tarjeta SD, todo funciona bien:escritura Android para carpeta de la tarjeta SD

package com.downloader; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import android.os.Environment; 
import android.util.Log; 

public class Downloader { 

    public void DownloadFile(String fileURL, String fileName) { 
     try { 
      File root = Environment.getExternalStorageDirectory(); 
      URL u = new URL(fileURL); 
      HttpURLConnection c = (HttpURLConnection) u.openConnection(); 
      c.setRequestMethod("GET"); 
      c.setDoOutput(true); 
      c.connect(); 
      FileOutputStream f = new FileOutputStream(new File(root, fileName)); 

      InputStream in = c.getInputStream(); 

      byte[] buffer = new byte[1024]; 
      int len1 = 0; 
      while ((len1 = in.read(buffer)) > 0) { 
       f.write(buffer, 0, len1); 
      } 
      f.close(); 
     } catch (Exception e) { 
      Log.d("Downloader", e.getMessage()); 
     } 

    } 
} 

Sin embargo, el uso de Environment.getExternalStorageDirectory(); significa que el archivo siempre se escribirá en la raíz /mnt/sdcard. ¿Es posible especificar una determinada carpeta para escribir el archivo?

Por ejemplo: /mnt/sdcard/myapp/downloads

Saludos

Eef

+12

También es necesario recordar agregar los permisos en el m Anifiesto para que esto funcione .. timemirror

Respuesta

149
File sdCard = Environment.getExternalStorageDirectory(); 
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2"); 
dir.mkdirs(); 
File file = new File(dir, "filename"); 

FileOutputStream f = new FileOutputStream(file); 
... 
+0

Cheers mate, funciona como un regalo. – RailsSon

+1

Asegúrese de utilizar todas las letras minúsculas en su directorio y nombres de archivos. – BeccaP

+1

¿Puedo saber lo que significa "/ dir1/dir2" y sin esto no puedo guardar mi archivo en sdcard ah? – AndroidOptimist

29

Añadir Permiso para Android Manifiesto

Añadir this WRITE_EXTERNAL_STORAGE permission a sus aplicaciones manifiestas.

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="your.company.package" 
    android:versionCode="1" 
    android:versionName="0.1"> 
    <application android:icon="@drawable/icon" android:label="@string/app_name"> 
     <!-- ... --> 
    </application> 
    <uses-sdk android:minSdkVersion="7" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
</manifest> 

Comprobar disponibilidad de almacenamiento externo

Siempre debe comprobar disponibilidad primero. Un fragmento del the official android documentation on external storage.

boolean mExternalStorageAvailable = false; 
boolean mExternalStorageWriteable = false; 
String state = Environment.getExternalStorageState(); 

if (Environment.MEDIA_MOUNTED.equals(state)) { 
    // We can read and write the media 
    mExternalStorageAvailable = mExternalStorageWriteable = true; 
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
    // We can only read the media 
    mExternalStorageAvailable = true; 
    mExternalStorageWriteable = false; 
} else { 
    // Something else is wrong. It may be one of many other states, but all we need 
    // to know is we can neither read nor write 
    mExternalStorageAvailable = mExternalStorageWriteable = false; 
} 

Utilice un FileWriter

Por último pero no menos importante olvidarse de la FileOutputStream y utilizar un FileWriter lugar. Más información sobre esa clase en el formulario the FileWriter javadoc. Es posible que desee agregar un poco más de manejo de errores aquí para informar al usuario.

// get external storage file reference 
FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
// Writes the content to the file 
writer.write("This\n is\n an\n example\n"); 
writer.flush(); 
writer.close(); 
+1

Los autores del libro Estoy leyendo recomienda utilizar un 'FileOutputStream' (bueno, no cubre las alternativas). ¿Por qué es mejor usar el 'FileWriter' en su lugar? ¿Es más rápido/más confiable/algo más? – aga

+3

@aga 'FileWriter' tiene métodos de conveniencia para escribir directamente cadenas, que no están presentes en un' FileOutputStream'. Si no está escribiendo archivos de texto, 'FileWriter' no es de mucha ayuda. De hecho, si estás escribiendo un archivo * image *, realmente no se puede hacer en absoluto con un 'FileWriter' Por supuesto, si * realmente * quieres una buena API para texto, envuelve tu' FileOutputStream' en un 'PrintStream' y tendrás todos los mismos métodos que' System.out'. –

2

encontrado la respuesta aquí - http://mytechead.wordpress.com/2014/01/30/android-create-a-file-and-write-to-external-storage/

Dice,

/** 

* Method to check if user has permissions to write on external storage or not 

*/ 

public static boolean canWriteOnExternalStorage() { 
    // get the state of your external storage 
    String state = Environment.getExternalStorageState(); 
    if (Environment.MEDIA_MOUNTED.equals(state)) { 
    // if storage is mounted return true 
     Log.v("sTag", "Yes, can write to external storage."); 
     return true; 
    } 
    return false; 
} 

y luego vamos a utilizar este código para escribir en realidad para el almacenamiento externo:

// get the path to sdcard 
File sdcard = Environment.getExternalStorageDirectory(); 
// to this path add a new directory path 
File dir = new File(sdcard.getAbsolutePath() + "/your-dir-name/"); 
// create this directory if not already created 
dir.mkdir(); 
// create the file in which we will write the contents 
File file = new File(dir, "My-File-Name.txt"); 
FileOutputStream os = outStream = new FileOutputStream(file); 
String data = "This is the content of my file"; 
os.write(data.getBytes()); 
os.close(); 

Y esto Lo es. Si ahora visita su carpeta/sdcard/your-dir-name /, verá un archivo llamado - My-File-Name.txt con el contenido especificado en el código.

PS: - Se necesita el siguiente permiso -

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

El directorio '/ sdcard /' no es siempre la tarjeta SD. – CurlyCorvus

+0

Acepto a Curly. En mi teléfono, el método getExternalStorageDirectory devuelve un almacenamiento emulado, que no es la tarjeta SD. – Spindizzy

-1

Para descargar un archivo para descargar o carpeta de música de tarjeta SD

File downlodDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);// or DIRECTORY_PICTURES 

Y no se olvide de agregar éstos permiso manifiesto

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