Dhrupal
Dhrupal

Reputation: 1873

Download image and strore in sdcard folder

I want to download image from url and store in sdcard's folder.
If folder is not exist make folder and save it.
But its giving following exception:

java.io.FileNotFoundException: /mnt/sdcard (Is a directory)

Upvotes: 2

Views: 5646

Answers (6)

RobGThai
RobGThai

Reputation: 5969

The message is clear. /mnt/sdcard is a directory not a file. You need to create FileOutputStream that writes to a non-directory path.

For example:

//Setting up cache directory to store the image
File cacheDir=new File(context.getCacheDir(),"cache_folder");

// Check if cache folder exists, otherwise create folder. 
if(!cacheDir.exists())cacheDir.mkdirs();

// Setting up file to write the image to. 
File f=new File(cacheDir, "img.png");

// Open InputStream to download the image. 
InputStream is=new URL(url).openStream();

// Set up OutputStream to write data into image file. 
OutputStream os = new FileOutputStream(f);

HelperUtil.CopyStream(is, os);

...



/**
 * Copy all data from InputStream and write using OutputStream
 * @param is InputStream
 * @param os OutputStream
 */
public static void CopyStream(InputStream is, OutputStream os)
{
    final int buffer_size=1024;
    try
    {
        byte[] bytes=new byte[buffer_size];
        for(;;)
        {
          int count=is.read(bytes, 0, buffer_size);
          if(count==-1)
              break;
          os.write(bytes, 0, count);
        }
    }
    catch(Exception ex){}
}

Upvotes: 2

Khan
Khan

Reputation: 7605

try something like this

String image_URL="http://chart.apis.google.com/chart?chs=200x200&cht=qr&chl=http%3A%2F%2Fandroid-er.blogspot.com%2F";

String extStorageDirectory;
File file;
Bitmap bm;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
        file=new File(android.os.Environment.getExternalStorageDirectory(),"Your FolderName");
        extStorageDirectory = Environment.getExternalStorageDirectory().toString();
  }else{
        file=YourActivity.this.getCacheDir();
 }
if(!file.exists())
  file.mkdirs();


  extStorageDirectory+="Your FolderName/yourimagename.PNG";
  File imageFile = new File(extStorageDirectory);

  Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
  if(bitmap!=null){
  imageview.setImageBitmap(bitmap);
  }else{
    extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    BitmapFactory.Options bmOptions;
    bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1;
    bm = LoadImage(image_URL, bmOptions);
    imageview.setImageBitmap(bm);

    OutputStream outStream = null;
    file=new File(android.os.Environment.getExternalStorageDirectory(),"Your FolderName");

    file=new File(extStorageDirectory, "Your FolderName/yourimagename.PNG");
     try {
        outStream = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
        outStream.flush();
        outStream.close();



      } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
       e.printStackTrace();

      } catch (IOException e) {
         // TODO Auto-generated catch block
        e.printStackTrace();

      }
  }

where method are as

private Bitmap LoadImage(String URL, BitmapFactory.Options options)
 {      
  Bitmap bitmap = null;
  InputStream in = null;      
    try {
      in = OpenHttpConnection(URL);
      bitmap = BitmapFactory.decodeStream(in, null, options);
      in.close();
    } catch (IOException e1) {
   }
  return bitmap;              
}

 private InputStream OpenHttpConnection(String strURL) throws IOException{
    InputStream inputStream = null;
    URL url = new URL(strURL);
    URLConnection conn = url.openConnection();

  try{
   HttpURLConnection httpConn = (HttpURLConnection)conn;
   httpConn.setRequestMethod("GET");
   httpConn.connect();

    if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
       inputStream = httpConn.getInputStream();
      }
  }catch (Exception ex){ 
       Log.e("error",ex.toString());
       }
  return inputStream;
 }

Upvotes: 2

ankita gahoi
ankita gahoi

Reputation: 1562

use this

if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        File file=new File(Environment.getExternalStorageDirectory()+path);  

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100, bytes);
        byte b[] = bytes.toByteArray();
        try
        {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(b);
            fos.flush();
            fos.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

path will be your folder in sdcard and bitamp is object of image

Upvotes: 1

osayilgan
osayilgan

Reputation: 5893

Try this one, that will return the External memory if it is exist, otherwise it will return the phone memory directory. The constructor takes Context and the name of the folder that you want to create as parameters. And also try this link, its quite nice stuff about what you need. Image Loader

public class FileCache {

private File cacheDir;
private String applicationDirectory = Config.applicationMainFolder;

public FileCache(Context context, String folderName){
    //Find the dir to save cached images
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(context.getExternalFilesDir(null), applicationDirectory + folderName);
    else
        cacheDir = new File(context.getCacheDir(), applicationDirectory + folderName);
    if(!cacheDir.exists())
        cacheDir.mkdirs();
}

public File getFile(String url){
    String filename=String.valueOf(url.hashCode());
    File f = new File(cacheDir, filename);
    return f;
}

public void clear(){
    File[] files=cacheDir.listFiles();
    if(files==null)
        return;
    for(File f:files)
        f.delete();
}
}

Upvotes: 1

Furqi
Furqi

Reputation: 2403

BitmapFactory.Options bmOptions;
        bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;
        bm = LoadImage(image_url, bmOptions);
        extStorageDirectory = Environment.getExternalStorageDirectory()
                .toString() + "/image_folder";

        OutputStream outStream = null;

        File wallpaperDirectory = new File(extStorageDirectory);
        wallpaperDirectory.mkdirs();
        File outputFile = new File(wallpaperDirectory, "image.PNG");

        try {
            outStream = new FileOutputStream(outputFile);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }


        try {
            bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();


        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }
  private Bitmap LoadImage(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try {
    in = OpenHttpConnection(URL);
    bitmap = BitmapFactory.decodeStream(in, null, options);
    in.close();
} catch (IOException e1) {
}
return bitmap;
 }

  private InputStream OpenHttpConnection(String strURL) throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();

try {
    HttpURLConnection httpConn = (HttpURLConnection) conn;
    httpConn.setRequestMethod("GET");
    httpConn.connect();

    if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        inputStream = httpConn.getInputStream();
    }
} catch (Exception ex) {
}
return inputStream;
}

Upvotes: 1

Caner
Caner

Reputation: 59168

You are giving wrong path when triying to save the picture. IT seems that you use "/mnt/sdcard" whereas it should be something like "/mnt/sdcard/image.jpg"

Upvotes: 1

Related Questions