How to write an sd card to a specific folder on Android.

Asked 2 years ago, Updated 2 years ago, 113 views

Below is the code for downloading files from my server. I write the download file to the root directory of the sd card, but it works well!

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

    }
}

But when you use Environment.getExternalStorageDirectory(); the file is always written to the root folder, that is, /mnt/sdcard Is it possible to write a file in a specific folder? For example, /mnt/sdcard/myapp/downloads

android java android-sdcard http download

2022-09-22 21:31

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

It's possible.


2022-09-22 21:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.