Android speichert Datei auf externem Speicher

Lesezeit: 8 Minuten

Android speichert Datei auf externem Speicher
Android-Droid

Ich habe ein kleines Problem mit dem Erstellen eines Verzeichnisses und dem Speichern einer Datei darin in meiner Android-Anwendung. Ich verwende diesen Code, um dies zu tun:

String filename = "MyApp/MediaTag/MediaTag-"+objectId+".png";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;

fos = new FileOutputStream(file);
fos.write(mediaTagBuffer);
fos.flush();
fos.close();

Aber es wirft eine Ausnahme:

java.io.FileNotFoundException: /mnt/sdcard/MyApp/MediaCard/MediaCard-0.png (Keine solche Datei oder Verzeichnis)

auf dieser Zeile: fos = new FileOutputStream(file);

Wenn ich den Dateinamen setze auf: "MyApp/MediaTag-"+objectId+" Es funktioniert, aber wenn ich versuche, die Datei zu erstellen und in einem anderen Verzeichnis zu speichern, wird die Ausnahme ausgelöst. Also irgendwelche Ideen was ich falsch mache?

Und noch eine Frage: Gibt es eine Möglichkeit, meine Dateien im externen Speicher privat zu machen, damit der Benutzer sie nicht in der Galerie sehen kann, nur wenn er sein Gerät als verbindet Disk Drive?

1646628793 440 Android speichert Datei auf externem Speicher
RajaReddy PolamReddy

Verwenden Sie diese Funktion, um Ihre Bitmap auf der SD-Karte zu speichern

private void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
     if (!myDir.exists()) {
                    myDir.mkdirs();
                }
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ())
      file.delete (); 
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
         e.printStackTrace();
    }
}

und fügen Sie dies im Manifest hinzu

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

BEARBEITEN: Wenn Sie diese Zeile verwenden, können Sie gespeicherte Bilder in der Galerieansicht sehen.

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                         Uri.parse("file://" + Environment.getExternalStorageDirectory())));

schau dir auch diesen Link an http://rajareddypolam.wordpress.com/?p=3&preview=true

  • Sie sollten immer noch verwenden Environment.getExternalStorageDirectory() anstatt /sdcard.

    – Che Jami

    25. Oktober 2011 um 10:41 Uhr

  • Es speichert nur in Ihrem Ordner, es zeigt in der Kamera an, dass Sie Bilder automatisch mit der Kamera aufnehmen, es wird automatisch in der Kamera gespeichert.

    – RajaReddy PolamReddy

    12. April 2013 um 11:43 Uhr

  • Benutzen Sie bitte finally und fangen Sie nicht generisch Exception

    – Herr_und_Frau_D

    28. Juli 2013 um 18:01 Uhr

  • @LiamGeorgeBetsworth Alle oben beschriebenen Verhaltensweisen funktionieren wie es ist in vor KitKat.

    – Muhammad Babar

    5. Juni 2014 um 10:12 Uhr


  • Es ist nicht geeignet zu verwenden Intent.ACTION_MEDIA_MOUNTED und funktioniert nicht auf KitKat. Die korrekte Sendeabsicht ist new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file) )

    – Anthony Garcia-Labiad

    2. Januar 2016 um 18:52 Uhr

Der von RajaReddy präsentierte Code funktioniert nicht mehr für KitKat

Dieser tut (2 Änderungen):

private void saveImageToExternalStorage(Bitmap finalBitmap) {
    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-" + n + ".jpg";
    File file = new File(myDir, fname);
    if (file.exists())
        file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }


    // Tell the media scanner about the new file so that it is
    // immediately available to the user.
    MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
    });

}

  • Ich bekomme uri null?

    – Mukesh Lokare

    12. Oktober 2017 um 10:25 Uhr

  • Teilen Sie dem Medienscanner die neue Datei mit, damit sie dem Benutzer sofort zur Verfügung steht – es rettet mir den Tag

    – Saiful Islam Sajib

    11. Dezember 2018 um 4:24 Uhr

Android speichert Datei auf externem Speicher
João Cartucho

Update 2018, SDK >= 23.

Jetzt sollten Sie auch überprüfen, ob der Benutzer die Berechtigung zum externen Speicher erteilt hat, indem Sie Folgendes verwenden:

public boolean isStoragePermissionGranted() {
    String TAG = "Storage Permission";
    if (Build.VERSION.SDK_INT >= 23) {
        if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG, "Permission is granted");
            return true;
        } else {
            Log.v(TAG, "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

public void saveImageBitmap(Bitmap image_bitmap, String image_name) {
    String root = Environment.getExternalStorageDirectory().toString();
    if (isStoragePermissionGranted()) { // check or ask permission
        File myDir = new File(root, "/saved_images");
        if (!myDir.exists()) {
            myDir.mkdirs();
        }
        String fname = "Image-" + image_name + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile(); // if file already exists will do nothing
            FileOutputStream out = new FileOutputStream(file);
            image_bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        MediaScannerConnection.scanFile(this, new String[]{file.toString()}, new String[]{file.getName()}, null);
    }
}

und fügen Sie natürlich die hinzu AndroidManifest.xml:

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

1646628797 940 Android speichert Datei auf externem Speicher
Entwickler Sabby

Dafür benötigen Sie eine Erlaubnis

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

und Methode:

public boolean saveImageOnExternalData(String filePath, byte[] fileData) {

    boolean isFileSaved = false;
    try {
        File f = new File(filePath);
        if (f.exists())
            f.delete();
        f.createNewFile();
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(fileData);
        fos.flush();
        fos.close();
        isFileSaved = true;
        // File Saved
    } catch (FileNotFoundException e) {
        System.out.println("FileNotFoundException");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("IOException");
        e.printStackTrace();
    }
    return isFileSaved;
    // File Not Saved
}

Stellen Sie sicher, dass Ihre App über die erforderlichen Berechtigungen verfügt, um in den externen Speicher schreiben zu dürfen: http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE

In Ihrer Manifest-Datei sollte es ungefähr so ​​​​aussehen:

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

1646628799 33 Android speichert Datei auf externem Speicher
Herr_und_Frau_D

Versuche dies :

  1. Überprüfen Sie das externe Speichergerät
  2. Datei schreiben
  3. Datei lesen
public class WriteSDCard extends Activity {

    private static final String TAG = "MEDIA";
    private TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.TextView01);
        checkExternalMedia();
        writeToSDFile();
        readRaw();
    }

    /**
     * Method to check whether external media available and writable. This is
     * adapted from
     * http://developer.android.com/guide/topics/data/data-storage.html
     * #filesExternal
     */
    private void checkExternalMedia() {
        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // Can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // Can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            // Can't read or write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }
        tv.append("\n\nExternal Media: readable=" + mExternalStorageAvailable
            + " writable=" + mExternalStorageWriteable);
    }

    /**
     * Method to write ascii text characters to file on SD card. Note that you
     * must add a WRITE_EXTERNAL_STORAGE permission to the manifest file or this
     * method will throw a FileNotFound Exception because you won't have write
     * permission.
     */
    private void writeToSDFile() {
        // Find the root of the external storage.
        // See http://developer.android.com/guide/topics/data/data-
        // storage.html#filesExternal
        File root = android.os.Environment.getExternalStorageDirectory();
        tv.append("\nExternal file system root: " + root);
        // See
        // http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
        File dir = new File(root.getAbsolutePath() + "/download");
        dir.mkdirs();
        File file = new File(dir, "myData.txt");
        try {
            FileOutputStream f = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(f);
            pw.println("Hi , How are you");
            pw.println("Hello");
            pw.flush();
            pw.close();
            f.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.i(TAG, "******* File not found. Did you"
                + " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
        } catch (IOException e) {
            e.printStackTrace();
        }
        tv.append("\n\nFile written to " + file);
    }

    /**
     * Method to read in a text file placed in the res/raw directory of the
     * application. The method reads in all lines of the file sequentially.
     */
    private void readRaw() {
        tv.append("\nData read from res/raw/textfile.txt:");
        InputStream is = this.getResources().openRawResource(R.raw.textfile);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer
        // size
        // More efficient (less readable) implementation of above is the
        // composite expression
        /*
         * BufferedReader br = new BufferedReader(new InputStreamReader(
         * this.getResources().openRawResource(R.raw.textfile)), 8192);
         */
        try {
            String test;
            while (true) {
                test = br.readLine();
                // readLine() returns null if no more lines in the file
                if (test == null) break;
                tv.append("\n" + "    " + test);
            }
            isr.close();
            is.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        tv.append("\n\nThat is all");
    }
}

Android speichert Datei auf externem Speicher
Zar E. Ahmer

Ich habe eine AsyncTask zum Speichern von Bitmaps erstellt.

public class BitmapSaver extends AsyncTask<Void, Void, Void>
{
    public static final String TAG ="BitmapSaver";

    private Bitmap bmp;

    private Context ctx;

    private File pictureFile;

    public BitmapSaver(Context paramContext , Bitmap paramBitmap)
    {
        ctx = paramContext;

        bmp = paramBitmap;
    }

    /** Create a File for saving an image or video */
    private  File getOutputMediaFile()
    {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this. 
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Android/data/"
                + ctx.getPackageName()
                + "/Files"); 

        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                return null;
            }
        } 
        // Create a media file name
        String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
        File mediaFile;
            String mImageName="MI_"+ timeStamp +".jpg";
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
        return mediaFile;

    } 
    protected Void doInBackground(Void... paramVarArgs)
    {   
        this.pictureFile = getOutputMediaFile();

        if (this.pictureFile == null) { return null; }

        try
        {
            FileOutputStream localFileOutputStream = new FileOutputStream(this.pictureFile);
            this.bmp.compress(Bitmap.CompressFormat.PNG, 90, localFileOutputStream);
            localFileOutputStream.close();
        }
        catch (FileNotFoundException localFileNotFoundException)
        {
            return null;
        }
        catch (IOException localIOException)
        {
        }
        return null;
    }

    protected void onPostExecute(Void paramVoid)
    {
        super.onPostExecute(paramVoid);

        try
        {
            //it will help you broadcast and view the saved bitmap in Gallery
            this.ctx.sendBroadcast(new Intent("android.intent.action.MEDIA_MOUNTED", Uri
                    .parse("file://" + Environment.getExternalStorageDirectory())));

            Toast.makeText(this.ctx, "File saved", 0).show();

            return;
        }
        catch (Exception localException1)
        {
            try
            {
                Context localContext = this.ctx;
                String[] arrayOfString = new String[1];
                arrayOfString[0] = this.pictureFile.toString();
                MediaScannerConnection.scanFile(localContext, arrayOfString, null,
                        new MediaScannerConnection.OnScanCompletedListener()
                        {
                            public void onScanCompleted(String paramAnonymousString ,
                                    Uri paramAnonymousUri)
                            {
                            }
                        });
                return;
            }
            catch (Exception localException2)
            {
            }
        }
    }
}

  • Wie kann ich ein GIF-Bild speichern?

    – Vishal Senjaliya

    3. Oktober 2016 um 10:10 Uhr

  • Das GIF-Bild enthält mehrere Bilder. Sie müssen diese Frames zuerst trennen, dann können Sie diese Methode verwenden. Es ist meine Meinung.

    – Zar E. Ahmer

    10. Oktober 2016 um 6:02 Uhr

  • Ich habe es von stackoverflow.com/questions/39826400/…

    – Vishal Senjaliya

    10. Oktober 2016 um 6:19 Uhr

962920cookie-checkAndroid speichert Datei auf externem Speicher

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy