Sun
Sun

Reputation: 6888

create folder into sd card programmatically

i am trying to put audio mp3 file into Awesome Music folder, but always getting under Music directory.

see below screenshot:

enter image description here

code i have written:

private static String fileName = "MyMusic";
    private static final String MY_URL = "http://www.virginmegastore.me/Library/Music/CD_001214/Tracks/Track1.mp3";
static File mediaStorageDir ;

 // folder name
                mediaStorageDir = new File(
                        Environment
                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),
                                "/Awesome Music/");

                if (!mediaStorageDir.exists()) {
                    if (!mediaStorageDir.mkdirs()) {
                        Log.d("App", "failed to create directory");                  
                    }
                }

                // Output stream to write file
                OutputStream output = new FileOutputStream(mediaStorageDir + fileName + ".mp3");

Questions:

  1. why its not storing mp3 into Awesome Music folder ?

  2. why its showing Awesome Music as prefix of song name ?

I am using this tutorial

complete code:

public class MainActivity extends Activity {

private static String fileName = "MyMusic";
private static final String MY_URL = "http://www.virginmegastore.me/Library/Music/CD_001214/Tracks/Track1.mp3";

private Button download;

private ProgressDialog pDialog;
static File mediaStorageDir ;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    download = (Button) findViewById(R.id.download);

    download.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            new DownloadFileFromURL().execute(MY_URL);
        }
    });

}

/**
 * Showing Dialog
 * */
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type:
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}

public void downloadStreams() {
    try {
        URL url = new URL(MY_URL);
        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

        File outputFile = new File(MY_URL, fileName);
        FileOutputStream fos = new FileOutputStream(outputFile);

        InputStream is = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len1);
        }
        fos.close();
        is.close();
    } catch (IOException e) {
        Log.e("log_tag", "Error: " + e);
    }
    Log.v("log_tag", "Check: ");
}

class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }

    /**
     * Downloading file in background thread
     * */
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(),
                    8192);

            // folder name
            mediaStorageDir = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),
                            "/Awesome Music/");
            Log.d("mediaStorageDir", mediaStorageDir.toString());

            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("App", "failed to create directory");                  
                }
            }
            Log.d("before>>fileName", fileName);
            // Output stream to write file
            OutputStream output = new FileOutputStream(mediaStorageDir + fileName + ".mp3");
            Log.d("after>>fileName", fileName);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        dismissDialog(progress_bar_type);
    }

}

}

Log:-

D/mediaStorageDir(22616): /storage/sdcard0/Music/Awesome Music
D/before>>fileName(22616): MyMusic
D/after>>fileName(22616): MyMusic

Upvotes: 0

Views: 11362

Answers (4)

GrIsHu
GrIsHu

Reputation: 23638

You are always getting that folder inside music directory because you have written code to get the path of that music directory.

 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)

If you want to create folder directly into the SDcard then you have to just write

   Environment.getExternalStorageDirectory()

which will give you the path upto the sdcard.

EDITED:

If you want to put your file inside the folder which resides in music directory then try as below:

  mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
    + File.separator + "Awesome Music");

Change your code as below:

     // folder name
        mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),
                        "/Awesome Music/");
        Log.d("mediaStorageDir", mediaStorageDir.toString());

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("App", "failed to create directory");                  
            }
        }
         String filename=mediaStorageDir + fileName + ".mp3";//String contains file name
         File newfile=new File(mediaStorageDir,filename);

        OutputStream output = new FileOutputStream(newfile);
        Log.d("after>>fileName", fileName);

        byte data[] = new byte[1024];
        long total = 0;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            // After this onProgressUpdate will be called
            publishProgress("" + (int) ((total * 100) / lenghtOfFile));

            // writing data to file
            output.write(data, 0, count);
        }

Check out my blog Android External storage structure which will guide you about the structure of android folders.

Upvotes: 0

Ramz
Ramz

Reputation: 7164

you are downloading some mp3 files right,ok then please try this code

URL url = new URL("your url");
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(),
                    8192);
File gallery = new File("/sdcard/Awesome Music/");

    String filename="somefilename.mp3"

if (!gallery.exists()) {
                gallery.mkdir();
            }
            String datafile = "/sdcard/Awesome Music/" + filename;
            // Output stream to write file
            OutputStream output = new FileOutputStream(datafile);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;


                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

Hope this will help you,Thank you

Upvotes: 1

iTech
iTech

Reputation: 18460

Just replace the , with + to have the full path of the parent folder in which your files will be stored

mediaStorageDir = new File(
  Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)+
                            "/Awesome Music/");

Upvotes: 0

Hakan Serce
Hakan Serce

Reputation: 11266

Instead of Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)

use Environment.getExternalStorageDirectory()

Upvotes: 1

Related Questions