Jak zapisać do folderu na karcie SD w Androidzie?

Używam poniższego kodu, aby pobrać plik z mojego serwera, a następnie zapisać go do katalogu głównego karty SD, wszystko działa dobrze:

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());
        }

    }
}

Jednak użycie Environment.getExternalStorageDirectory(); oznacza, że plik będzie zawsze zapisywany do katalogu głównego /mnt/sdcard. Czy można określić określony folder do zapisu pliku?

Na przykład: /mnt/sdcard/myapp/downloads

Author: Josh Correia, 2010-08-23

4 answers

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);
...
 160
Author: plugmind,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-01 21:43:02

Dodaj uprawnienia do manifestu Androida

Dodaj to Pozwolenie WRITE_EXTERNAL_STORAGE do manifestu aplikacji.

<?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> 

Sprawdź dostępność zewnętrznego magazynu

Zawsze należy najpierw sprawdzić dostępność. Fragment z oficjalnej dokumentacji Androida na zewnętrznej pamięci masowej .

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;
}

Użyj Filewriter

W końcu, ale nie mniej ważne, zapomnij o FileOutputStream i użyj FileWriter zamiast tego. Więcej informacji na temat formularza zajęć FileWriter javadoc . Możesz dodać więcej obsługi błędów tutaj, aby poinformować użytkownika.

// 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();
 30
Author: hcpl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-20 17:18:41

Tutaj znalazłem odpowiedź - http://mytechead.wordpress.com/2014/01/30/android-create-a-file-and-write-to-external-storage/

Jest napisane,

/**

* 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;
}

A następnie użyjmy tego kodu do zapisu do pamięci zewnętrznej:

// 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();
I to jest to. Jeśli teraz odwiedzisz swój/sdcard/ Twój-dir-name / folder zobaczysz plik o nazwie-My-File-Name.txt z zawartością określoną w kodzie.

PS: - potrzebujesz następującej zgody -

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 2
Author: alchemist,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-31 12:17:13

Aby pobrać plik do pobrania lub folder Muzyczny w SDCard

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

I nie zapomnij dodać tych uprawnień w manifeście

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
 -1
Author: AndroidGeek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-05 15:31:42