Pertanyaan Android menulis ke folder kartu sd


Saya menggunakan kode berikut untuk mengunduh file dari server saya lalu menuliskannya ke direktori root kartu sd, semuanya berfungsi dengan baik:

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

    }
}

Namun, menggunakan Environment.getExternalStorageDirectory(); artinya file akan selalu menulis ke root /mnt/sdcard. Apakah mungkin untuk menentukan folder tertentu untuk menulis file ke?

Sebagai contoh: /mnt/sdcard/myapp/downloads

Tepuk tangan

Eef


76
2017-08-23 21:24


asal


Jawaban:


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);
...

152
2017-08-23 21:36



Tambahkan Izin ke Manifes Android

Menambahkan izin WRITE_EXTERNAL_STORAGE ini ke manifes aplikasi Anda.

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

Periksa ketersediaan penyimpanan eksternal

Anda harus selalu memeriksa ketersediaan terlebih dahulu. Potongan dari dokumentasi Android resmi di penyimpanan eksternal.

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

Gunakan Filewriter

Pada akhirnya tetapi tidak sedikit melupakan tentang FileOutputStream dan gunakan a FileWriter sebagai gantinya. Informasi lebih lanjut tentang bentuk kelas itu javadoc FileWriter. Anda mungkin ingin menambahkan lebih banyak penanganan kesalahan di sini untuk memberi tahu pengguna.

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

29
2017-11-20 17:18



Temukan jawabannya di sini - http://mytechead.wordpress.com/2014/01/30/android-create-a-file-and-write-to-external-storage/

Ia mengatakan,

/**

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

lalu gunakan kode ini untuk benar-benar menulis ke penyimpanan eksternal:

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

Dan ini dia. Jika sekarang Anda mengunjungi folder / sdcard / nama-dir / folder Anda, Anda akan melihat file bernama - My-File-Name.txt dengan konten yang ditentukan dalam kode.

PS: - Anda perlu izin berikut -

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

2
2018-01-30 08:05



Untuk mengunduh file ke Unduh atau Folder Musik Di SDCard 

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

Dan jangan lupa untuk menambahkan izin ini dalam manifes

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

-1
2017-10-05 15:31