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

时间:2019-02-04 06:02:18

标签: android

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

这是下载功能

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

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;
     }
  }

答案 2 :(得分: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);


   }


  }

答案 3 :(得分: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));
}

答案 4 :(得分:0)

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