簡體   English   中英

如何下載內部存儲中特定文件夾中的文件

[英]How to download the files in specific folder in internal storage

我正在嘗試在手機的內部存儲中創建一個單獨的文件夾,以便應用程序下載文件。 但該文件夾並未在手機中創建。 是什么原因? 此外,我的應用程序中還有另一個問題,即單擊下載按鈕時未下載照片。

這是下載功能

    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 studio中使用內部存儲首先在manifest中添加權限像這樣:

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

和異步類:

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


   }


  }

用於創建文件夾

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" />

更新

將文件保存到內部存儲時,可以通過調用方法獲取相應的目錄作為文件

獲取文件目錄()

 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

試試這個代碼:

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

在此方法中傳遞要下載的圖像的 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));
}

將所需的權限添加到AndroidManifest.xml文件。

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

為應用程序添加requestLegacyExternalStorage

<application
            android:requestLegacyExternalStorage="true">
</application>

將以下代碼段添加到MainActivity.java

File f = new File(Environment.getExternalStorageDirectory(), "My folder");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            try {
               Files.createDirectory(Paths.get(f.getAbsolutePath()));
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            }
        } else {
            f.mkdir();
            f.mkdirs();
            Toast.makeText(getApplicationContext(), f.getPath(), Toast.LENGTH_LONG).show();
        }

現在,觸發下載的代碼類似於:

String url="Here download Url paste";

DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url.toString()));

request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.allowScanningByMediaScanner();
request.setDestinationInExternalPublicDir("/My folder", fileName);

downloadManager.enqueue(request);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM