以编程方式将文件夹创建到SD卡中

时间:2014-03-15 07:11:09

标签: android

我正在尝试将音频mp3文件放入Awesome Music文件夹,但总是在音乐目录下。

见下面的截图:

enter image description here

我编写的代码:

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

问题:

  1. 为什么它不将mp3存储到Awesome Music文件夹中?

  2. 为什么它将Awesome Music显示为歌曲名称的前缀?

  3. 我正在使用this教程

    完整代码:

    公共类MainActivity扩展了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);
        }
    
    }
    

    }

    日志: -

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

4 个答案:

答案 0 :(得分:1)

而不是Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)

使用Environment.getExternalStorageDirectory()

答案 1 :(得分:1)

你正在下载一些mp3文件,好的,请试试这段代码

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

希望这会对你有所帮助,谢谢你

答案 2 :(得分:0)

只需将,替换为+,即可获得存储文件的父文件夹的完整路径

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

答案 3 :(得分:0)

您总是在音乐目录中获取该文件夹,因为您已编写代码来获取该音乐目录的路径。

 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)

如果要直接在SD卡中创建文件夹,则必须编写

   Environment.getExternalStorageDirectory()

将为您提供直达SD卡的路径。

<强>编辑:

如果您想将文件放在音乐目录中的文件夹中,请尝试以下操作:

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

更改您的代码如下:

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

查看我的博客Android External storage structure,它将指导您了解Android文件夹的结构。