如何下载内部存储中特定文件夹中的文件

问题描述 投票:0回答:4

我正在尝试在手机的内部存储中创建一个单独的文件夹,以便应用程序在其上下载文件。但是手机中没有创建该文件夹。是什么原因?此外,我的应用程序中还有另一个问题,即单击下载按钮时未下载照片。

这是下载功能

    public void download() {
    for (MediaModel item : Items) {

       if (item.isSelected) {

            Log.d("check", "download");
            final String url = item.getFullDownloadURL();
            BaseDownloadTask task = FileDownloader.getImpl().create(url);
            task.setListener(mFileDownloadListener)
            .setPath(Environment.getDataDirectory() + "/" + Constants.STORED_FOLDER, true)
                    .setAutoRetryTimes(1)
                    .setCallbackProgressTimes(0)
                    .asInQueueTask()
                    .enqueue();

            if (FileDownloader.getImpl().start(mFileDownloadListener, true)) {
                item.setTaskId(task.getId());
                item.setStatus(ItemStatus.DOWNLOADING);
                Logging.e(TAG, "start download task: " + task.getId());
            } else {
                item.setTaskId(task.getId());
                item.setStatus(ItemStatus.NORMAL);
                Logging.e(TAG, "error download task: " + task.getId());
            }
        }
    }
}
android
4个回答
0
投票

在Android studio中使用内部存储首先在清单中添加权限如下:

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

然后在内部存储中创建新目录使用这行代码:

   File sdCardRoot = new File(Environment.getExternalStorageDirectory(), "MyProfile");

        if (!sdCardRoot.exists()) {
            sdCardRoot.mkdirs();
        }

        Log.e("check_path", "" + sdCardRoot.getAbsolutePath());

这是我的完整代码:

在此代码中,如果目录不存在,则检查目录是否存在然后创建目录并使用asyntask从URL下载图像

在这个例子中,我使用了Java语言

  MyAsyncTasks asyncTasks = new MyAsyncTasks();
                asyncTasks.execute(Imageurl);

和AsyncClass:

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

File sdCardRoot;

@Override
protected String doInBackground(String... strings) {

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strings[0]);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();


        sdCardRoot = new File(Environment.getExternalStorageDirectory(), "MyProfile");

        if (!sdCardRoot.exists()) {
            sdCardRoot.mkdirs();
        }

        Log.e("check_path", "" + sdCardRoot.getAbsolutePath());

        String fileName =
                strings[0].substring(strings[0].lastIndexOf('/') + 1, strings[0].length());
        Log.e("dfsdsjhgdjh", "" + fileName);
        File imgFile =
                new File(sdCardRoot, fileName);
        if (!sdCardRoot.exists()) {
            imgFile.createNewFile();
        }
        InputStream inputStream = urlConnection.getInputStream();
        int totalSize = urlConnection.getContentLength();
        FileOutputStream outPut = new FileOutputStream(imgFile);
        int downloadedSize = 0;
        byte[] buffer = new byte[2024];
        int bufferLength = 0;
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            outPut.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            Log.e("Progress:", "downloadedSize:" + Math.abs(downloadedSize * 100 / totalSize));
        }
        Log.e("Progress:", "imgFile.getAbsolutePath():" + imgFile.getAbsolutePath());

        Log.e(TAG, "check image path 2" + imgFile.getAbsolutePath());

        mImageArray.add(imgFile.getAbsolutePath());
        outPut.close();
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("checkException:-", "" + e);
    }
    return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    imagecount++;
    Log.e("check_count", "" + totalimagecount + "==" + imagecount);
    if (totalimagecount == imagecount) {
        pDialog.dismiss();
        imagecount = 0;
    }
    Log.e("ffgnjkhjdh", "checkvalue checkvalue" + checkvalue);


   }


  }

0
投票

试试这段代码:

 private class DownloadingTask extends AsyncTask<Void, Void, Void> {

    File apkStorage = null;
    File outputFile = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog=new ProgressDialog(context);
        progressDialog.setMessage("Downloading...");
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(Void result) {
        try {
            if (outputFile != null) {
                progressDialog.dismiss();
                CDToast.makeText(context, context.getResources().getString(R.string.downloaded_successfully), CDToast.LENGTH_SHORT, CDToast.TYPE_SUCCESS).show();
                Notification();
                vibrateDevice(100);
            } else {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                    }
                }, 3000);

                CDToast.makeText(context, context.getResources().getString(R.string.download_failed), CDToast.LENGTH_SHORT, CDToast.TYPE_ERROR).show();


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

            //Change button text if an exception occurs

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                }
            }, 3000);
            Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());

        }


        super.onPostExecute(result);
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            URL url = new URL(downloadUrl);//Create Download URl
            HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
            c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
            c.connect();//connect the URL Connection

            //If Connection response is not OK then show Logs
            if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
                Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
                        + " " + c.getResponseMessage());

            }


            //Get File if SD card is present
            if (new CheckForSDCard().isSDCardPresent()) {

                apkStorage = new File(
                        Environment.getExternalStorageDirectory() + "/"
                                + "New_Folder_Name_Here");
            } else
                Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();

            //If File is not present create directory
            if (!apkStorage.exists()) {
                apkStorage.mkdir();
                Log.e(TAG, "Directory Created.");
            }

            outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File

            //Create New File if not present
            if (!outputFile.exists()) {
                outputFile.createNewFile();
                Log.e(TAG, "File Created");
            }

            FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location

            InputStream is = c.getInputStream();//Get InputStream for connection

            byte[] buffer = new byte[1024];//Set buffer type
            int len1 = 0;//init length
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);//Write new file
            }

            //Close all connection after doing task
            fos.close();
            is.close();

        } catch (Exception e) {

            //Read exception if something went wrong
            e.printStackTrace();
            outputFile = null;
            Log.e(TAG, "Download Error Exception " + e.getMessage());
        }

        return null;
    }
}

检查SD卡:

public class CheckForSDCard {


//Check If SD Card is present or not method
public boolean isSDCardPresent() {
    if (Environment.getExternalStorageState().equals(

            Environment.MEDIA_MOUNTED)) {
        return true;
    }
    return false;
     }
  }

0
投票

用于创建文件夹

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Your Folder Name";
    File folder = new File(path);
    if (!folder.exists()) {
        folder.mkdir();
    }

也请参考这个答案:https://stackoverflow.com/a/35471045/9060917

更新

public void download() {
    for (MediaModel item : Items) {
        if (item.isSelected) {
            File file = new File(getFilesDir(),"Your directory name");
if(!file.exists()){
    file.mkdir();
}

try{
    Log.d("check", "download");
            final String url = item.getFullDownloadURL();
            BaseDownloadTask task = FileDownloader.getImpl().create(url);
            task.setListener(mFileDownloadListener)
                .setPath(file.getAbsolutePath(), true)
                .setAutoRetryTimes(1)
                .setCallbackProgressTimes(0)
                .asInQueueTask()
                .enqueue();

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

}

        if (FileDownloader.getImpl().start(mFileDownloadListener, true)) {
            item.setTaskId(task.getId());
            item.setStatus(ItemStatus.DOWNLOADING);
            Logging.e(TAG, "start download task: " + task.getId());
        } else {
            item.setTaskId(task.getId());
            item.setStatus(ItemStatus.NORMAL);
            Logging.e(TAG, "error download task: " + task.getId());
            }
        }
    }
}

我希望你在清单中添加这些权限

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

更新

将文件保存到内部存储时,可以通过调用方法获取相应的目录作为文件

getFilesDir()

 File directory = context.getFilesDir();
 File file = new File(directory, filename);

或者,您可以调用openFileOutput()来获取写入内部目录中文件的FileOutputStream。例如,以下是如何将一些文本写入文件:

 String filename = "myfile";
 String fileContents = "Hello world!";
 FileOutputStream outputStream;

 try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContents.getBytes());
outputStream.close();
 } catch (Exception e) {
e.printStackTrace();
}

更多参考

https://developer.android.com/training/data-storage/files#java


0
投票

在此方法中传递要下载的图像的URL。

  /*--Download Image in Storage--*/
public void downloadImage(String URL) {
    final Long reference;
    downloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse(URL);
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setTitle("AppName");
    request.setDestinationInExternalPublicDir(String.format("%s/%s", Environment.getExternalStorageDirectory(),
            getString(R.string.app_name)), "FileName.jpg");
    Log.i("myi", "downloadImage: " + request.setDestinationInExternalPublicDir(String.format("%s/%s", Environment.getExternalStorageDirectory(),
            getString(R.string.app_name)), "FileName.jpg"));

    request.setVisibleInDownloadsUi(true);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    reference = downloadManager.enqueue(request);

    Log.d("download", "Image Download : " + reference);

    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                Toast.makeText(this, "Image Downloaded Successfully ", Toast.LENGTH_LONG);
            } catch (Exception e) {
            }
        }
    };
    getApplicationContext().registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
© www.soinside.com 2019 - 2024. All rights reserved.