2010-05-24 22 views
7

Usando el data-storage page in the docs, he intentado almacenar algunos datos en la tarjeta SD. Este es mi código:Almacenamiento de datos en la tarjeta SD en Android

// Path to write files to 
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
        "/Android/data/"+ctxt.getString(R.string.package_name)+"/files/"; 
    String fname = "mytest.txt"; 

    // Current state of the external media 
    String extState = Environment.getExternalStorageState(); 

    // External media can be written onto 
    if (extState.equals(Environment.MEDIA_MOUNTED)) 
    { 
     try { 
      // Make sure the path exists 
      boolean exists = (new File(path)).exists(); 
      if (!exists){ new File(path).mkdirs(); } 

      // Open output stream 
      FileOutputStream fOut = new FileOutputStream(path + fname); 

      fOut.write("Test".getBytes()); 

      // Close output stream 
      fOut.flush(); 
      fOut.close(); 

     } catch (IOException ioe) { 
      ioe.printStackTrace(); 
     } 

Cuando creo el nuevo FileOutputStream me sale una excepción FileNotFound. También noté que "mkdirs()" no parece crear el directorio.

¿Alguien puede decirme qué estoy haciendo mal?

Estoy probando un AVD con una tarjeta sd de 2GB y "hw.sdCard: yes", el Explorador de archivos de DDMS en Eclipse me dice que el único directorio en la tarjeta sd es "LOST.DIR".

Respuesta

2

Antes de leer o escribir en la tarjeta SD, no se olvide de comprobar la tarjeta SD está montado o no?

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) 
Cuestiones relacionadas