Как создать каталог и сохранить в нем файл из папки активов? - PullRequest
0 голосов
/ 27 января 2012

Я использую приведенный ниже код для копирования файла из ресурсов на SD-карту.

код:

  File file3 = new File("/sdcard/Alone.mp4");
    if(!(file3.exists())) {
        ArrayList<String> files = new ArrayList<String>();
        files.add("Alone.mp4");
        new myAsyncTask().execute(files);
    }

// AsyncTass for the Progress Dialog and to do Background Process
private class myAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {         
    ArrayList<String> files;         
    ProgressDialog dialog;         
    @Override         
    protected void onPreExecute() {             
        dialog = ProgressDialog.show(MainScreenActivity.this, "Speech Tutor", "Loading...");         
    }         
    @Override         
    protected Void doInBackground(ArrayList<String>... params) {              
        files = params[0];             
        for (int i = 0; i < files.size(); i++) {                 
            copyFileFromAssetsToSDCard(files.get(i));                
        }             return null;         
    }         
    @Override         
    protected void onPostExecute(Void result) {             
        dialog.dismiss();         
    }      
} 

    // Function to copy file from Assets to the SDCard
    public void copyFileFromAssetsToSDCard(String fileFromAssets){
        AssetManager is = this.getAssets();
        InputStream fis;
        try {

            fis = is.open(fileFromAssets);
            FileOutputStream fos;
//          if (!APP_FILE_PATH.exists()) {
//                APP_FILE_PATH.mkdirs();
//            }
            fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory(),fileFromAssets));
            byte[] b = new byte[8];
            int i;
            while ((i = fis.read(b)) != -1) {
                fos.write(b, 0, i);
            }
            fos.flush();
            fos.close();
            fis.close();
        } 
        catch (IOException e1) {
            e1.printStackTrace();
        }
    }

Теперь с помощью приведенного выше кода я могу скопировать файл из ресурсов на SDCard. но вместо этого я хочу сохранить файл копии в другом каталоге, доступном в SDCard.

Так как это сделать ??

Спасибо.

1 Ответ

2 голосов
/ 27 января 2012

Если вы хотите сохранить файл в какой-то определенной папке SDCard, то следующий код:

Environment.getExternalStorageDirectory () + "/ folderName /"

И если вы хотите создать новую папку, то следующий код:

String tempDir = Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.foldername) + "/";
    prepareDirectory(); 


private boolean prepareDirectory(){
    try {
        if (makedirs()){
            return true;
        } else {
            return false;
        }
    } catch (Exception e){
        e.printStackTrace();
        Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", 1000).show();
        return false;
    }
}

private boolean makedirs(){
    File tempdir = new File(tempDir);
    if (!tempdir.exists())
        tempdir.mkdirs();

    if (tempdir.isDirectory()){
        File[] files = tempdir.listFiles();
        for (File file : files){
            if (!file.delete()){
            }
        }
    }
    return (tempdir.isDirectory());
} 
...