android - storing image cache in internal memory a

2019-02-21 00:41发布

问题:

in my app i am trying to store the images in internal memory so that it can be used only in my app and cannot be seen in other ways.

In the following way i have stored the image cache in internal memory

File cacheDir = getApplicationContext().getDir("", Context.MODE_PRIVATE); 
File fileWithinMyDir = new File(cacheDir, "");

for(int i = 0; i < img.size(); i++)
{               
    String filename = String.valueOf(img.get(i).hashCode());
    String urlString = img.get(i);
    String PATH =  fileWithinMyDir + filename;
    DownloadFromUrl(PATH, urlString);
    img_path.add(PATH);
}

   private void DownloadFromUrl(String fileName, String urlStr) 
   {
      try 
      {
       URL url = new URL(urlStr);
       File file = new File(fileName);
       URLConnection ucon = url.openConnection();
       InputStream is = ucon.getInputStream();
       BufferedInputStream bis = new BufferedInputStream(is);
       ByteArrayBuffer baf = new ByteArrayBuffer(50);
       int current = 0;
       while ((current = bis.read()) != -1) 
       {
        baf.append((byte) current);
       }

       FileOutputStream fos = new FileOutputStream(file);
       fos.write(baf.toByteArray());
       fos.close();
    } 
    catch (IOException e) 
    {
        Log.e("download", e.getMessage());
    }
  }

img is an arraylist which contains the images url from which i am yet to download. img_path is an arraylist in which i am storing the path where the image cache is been stored.

The stored path seems to be as follows

/data/data/com.intr.store/app_1219784788

that path with my package name, is this a right one ? i have not given that app_ anywhere, but how does it came ?

in one of my other activity i want to load it in image view. I have tried it in the following way

File filePath = getFileStreamPath(pth);
        i.setImageDrawable(Drawable.createFromPath(filePath.toString()));

here pth is the path and i is the image view. But the app get crashed saying that

06-26 14:40:08.259: E/AndroidRuntime(6531): Caused by: java.lang.IllegalArgumentException: File /data/data/com.intr.store/app_1219784788 contains a path separator

回答1:

You have written wrong code.

Replace

File cacheDir = getApplicationContext().getDir("", Context.MODE_PRIVATE); 
File fileWithinMyDir = new File(cacheDir, "");

To

File fileWithinMyDir = getApplicationContext().getFilesDir();

Then

Replace

String PATH =  fileWithinMyDir + filename;

To

String PATH =  fileWithinMyDir.getAbsolutePath() + "/" +filename+".file extension";