java - Android 无法在内部存储上创建目录

标签 java android file android-internal-storage

我有一个应用程序可以从 URL 下载所有图像并将其保存到设备的隐藏文件夹中。如果手机有外部 SD 卡,它可以工作,否则应用程序会崩溃。所以我正在尝试转换我的代码以将图像存储在内部存储器中。

尽管我阅读了许多现有问题,但我无法解决我的问题。我不知道它是否可以是我的“request.setAllowedNetworkTypes”中的“.setDestinationInExternalPublicDir”导致问题的原因,可以吗?我应该如何更改我的代码?

我也尝试过使用 getDataDirectory 或 getFilesDir () 但我仍然有异常:

java.lang.IllegalStateException: Unable to create directory

这是我当前的代码,适用于具有外部 SD 卡的手机:

public class ImagesDownloader {

private static File imageDirectory = new File(Environment.getExternalStorageDirectory() + File.separator + ".Photo");
//or private static File imageDirectory; 

public static void downloadImages(Context context, List<MyList> imageList) {

        //here I tried to change the code like that (without success):
        //File imageDirectory = new File(Environment.getDataDirectory() + File.separator + ".Photo");
        //or
        //File imageDirectory = new File(context.getFilesDir() + File.separator + ".Photo");

        if (!imageDirectory.exists()) {
            if (!imageDirectory.mkdirs()) {
                Log.d("App", "failed to create directory");
            }
        }

        if(getImageFolderSize()==0){
            Iterator<MyList> iterator = imageList.iterator();
            while (iterator.hasNext()) {
                MyList MyList = iterator.next();
                String fileName = MyList.getFilename();
                String imgurl = "https://.../media/MyList/" + fileName;

                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);

                File imageFile = new File(Environment.getExternalStoragePublicDirectory(
                        imageDirectory.getPath()) + "/" + fileName);

                //and here how I wanted to change the code (without success):
                //File imageFile = = new File(imageDirectory.getPath() + "/" + fileName);

                if (!imageFile.canRead()) {

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

                    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                            .setAllowedOverRoaming(false)
                            .setTitle(fileName)
                            .setDescription("file description")
                            .setDestinationInExternalPublicDir(imageDirectory.getPath(), fileName)
                            .setVisibleInDownloadsUi(true);

                    BroadcastReceiver onComplete = new BroadcastReceiver() {
                        public void onReceive(Context ctxt, Intent intent) {
                        }
                    };

                    context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

                    if (downloadManager != null) {
                        downloadManager.enqueue(request);
                    }
                }
            }
        }
    }

    public static BitmapDescriptor getImgefromDeviceFolder(String fileName){

        File imageFile = new File(Environment.getExternalStoragePublicDirectory(
                imageDirectory.getPath()) + "/" + fileName);

        if (imageFile.canRead()) {
            Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
            return BitmapDescriptorFactory.fromBitmap(myBitmap);

        }
        return null;
    }

    static int getImageFolderSize(){

        File directory = Environment.getExternalStoragePublicDirectory(imageDirectory.getPath());
        if(directory.exists()){
            File[] files = directory.listFiles();
            if(files!=null){
                return files.length;
            }
        }
        return 0;
    }
}

第一次做文件归档,如有大错还请见谅

最佳答案

此代码适用于一张图片并且有效。

您可以测试它并为您的图像列表更改它。

  public static void downloadImages(Context context, String fileName ) {
    String storagePath = Environment.getExternalStorageDirectory()
        .getPath()
        + "/Directory_name/";
    //Log.d("Strorgae in view",""+storagePath);
    File f = new File(storagePath);
    if (!f.exists()) {
      f.mkdirs();
    }
    //storagePath.mkdirs();
    String pathname = f.toString();
    if (!f.exists()) {
      f.mkdirs();
    }
    //                Log.d("Storage ",""+pathname);
    DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
    String imgurl = "https://.../media/MyList/" + fileName;
    Uri uri = Uri.parse(imgurl);
      DownloadManager.Request request = new DownloadManager.Request(uri);
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

      request.setDestinationInExternalPublicDir("", uri.getLastPathSegment());
      Long referese = dm.enqueue(request);

      Toast.makeText(context, "Downloading...", Toast.LENGTH_SHORT).show();

  }

关于java - Android 无法在内部存储上创建目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58198881/

相关文章:

android - 如何发送音频文件以存储在服务器中

java - 注释处理器

java - 使用 IN 子句过滤 Spark Cassandra 连接器

android - Grafika 的 CameraCaptureActivity - 预览尺寸变化时相机预览失真

android - RecyclerView onBindViewHolder 在 Tab 布局中只调用一次

python 打开相对文件夹中以.txt结尾的所有文件

php - 在 for 循环期间将文件输入 ID 存储在变量内 | PHP

java - Git Eclipse 将源文件夹导入到项目中

java - LibGDX - 让 Actor 水平填充父级

python - 文件大小差异-python