java.io.FileNotFoundException:/storage/emulated/0/Folder/Images/Folder/210.JPG.jpg(无此类文件或目录)

时间:2018-09-03 12:09:48

标签: android file directory

使用Glide Library和“下载图像”从服务器下载图像并将其显示在Gridview中,并保存在“设备文件夹”中,但未创建文件夹。

FileNotFoundException。当项目调试时,调试将显示带有图像的完整目录路径,但未创建目录。我在清单文件中授予了WRITE_EXTERNAL_STORAGE权限。

public class GridViewAdapter extends ArrayAdapter {

    public Context context;
    public int resource;
    public ArrayList data = new ArrayList();

    int downloadedSize = 0, totalsize;

    float per = 0;

  public GridViewAdapter(Context context, int resource, ArrayList data) {
        super(context, resource, data);

        this.context = context;
        this.resource = resource;
        this.data = data;
    }

    public void setGridData(ArrayList data){
        this.data = data;
        notifyDataSetChanged();
    }


    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        View row = convertView;
        ViewHolder holder = null;

        TextView tv_loading;





        long refID;


        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(resource, parent, false);
            holder = new ViewHolder();
           //  holder.tv_loading = (TextView) row.findViewById(R.id.text);
            holder.image = (ImageView) row.findViewById(R.id.image);
           row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();
        }

        final ImageItem item = (ImageItem) data.get(position);


        Glide.with(context)
                .load(item.getImage())
                .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).override(200, 200))


                .into(holder.image);

        downloadFile(item.getImage(),item.getTitle(),item.getPathname());

        /*Glide.with(context)
                .asBitmap()
                .load(item.getImage())

                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        saveImage(resource,item.getPathname(),item.getImage());
                    }
                });*/


        return row;
    }


    static class ViewHolder {
        TextView tv_loading;
        ImageView image;
    }


    File downloadFile(String imageUrl, String Title,String PathName) {
        File file = null;
        try {





            URL url = new URL(imageUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();

            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(false);

            // connect
            urlConnection.connect();

            // set the path where we want to save the file
            File SDCardRoot = Environment.getExternalStorageDirectory();

            File dir = new File(SDCardRoot.getAbsolutePath() + "/Sankalp Pre School/Images/"+ Title);
            if (!dir.exists()) {
                dir.mkdirs();

            }

            Date d = new Date();
            CharSequence s = DateFormat
                    .format("yyyyMMdd", d.getTime());
            Random ran = new Random();
            int n = 10000;
            n = ran.nextInt(n);




            file = new File(dir,PathName +".jpg");




            FileOutputStream fileOutput = new FileOutputStream(file);

            // Stream used for reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();

            // this is the total size of the file which we are
            // downloading
            totalsize = urlConnection.getContentLength();
//            setText("Starting PDF download...");

            // create a buffer...
            byte[] buffer = new byte[1024 * 1024];
            int bufferLength = 0;

            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                per = ((float) downloadedSize / totalsize) * 100;
  /*              tv_loading.setText("Total PDF File size  : "
                        + (totalsize / 1024)
                        + " KB\n\nDownloading PDF " + (int) per
                        + "% complete");*/
            }
            // close the output stream when complete //
            fileOutput.close();
            //tv_loading.setText("Download Complete. Open PDF Application installed in the device.");
            Toast.makeText(context, "Download Complete.", Toast.LENGTH_SHORT).show();

        } catch (final MalformedURLException e) {
            //setTextError("Some error occured. Press back and try again.",
            e.printStackTrace();
            Toast.makeText(context, "Some error occured. Press back and try again.", Toast.LENGTH_SHORT).show();
              //      Color.RED);
        } catch (final IOException e) {
            e.printStackTrace();
            //setTextError("Some error occured. Press back and try again.",
            Toast.makeText(context, "Some error occured. Press back and try again.", Toast.LENGTH_SHORT).show();
                //    Color.RED);
        } catch (final Exception e) {
            e.printStackTrace();
            //setTextError(
                    //"Failed to download image. Please check your internet connection.",
                  //  Color.RED);
            Toast.makeText(context, "Failed to download image. Please check your internet connection.", Toast.LENGTH_SHORT).show();
        }
        return file;
    }

0 个答案:

没有答案