theiwarlock
theiwarlock

Reputation: 89

Saving image or file from url

I'm looking to save an image from a given url to a specified location on disk with a specified filename with java. I was told to convert to a byte array then save. Being new to java I feel completely lost with this right now.

I imagine I'll start by opening a connection to the url:

`String img_url = "some img url";
URL url = new URL(img_url);
URLConnection url_c = url.openConnection();`

Where do I go from here?

EDIT: I found out this implementation should save content regardless of the type. So if the url is to an image is should save or if the url is to a .doc or .pdf it should save it.

Upvotes: 0

Views: 3601

Answers (1)

Raghunandan
Raghunandan

Reputation: 133560

File direct = new File(Environment.getExternalStorageDirectory() + "/urfoldername/");
if(!direct.exists())
               {
                   direct.mkdir(); //directory is created;

               }
 file = new File("/sdcard/urfoldername/"+fileName);
 InputStream input = new BufferedInputStream(url.openStream());
 OutputStream output = new FileOutputStream(file);
 byte data[] = new byte[1024];
         while ((count = input.read(data)) != -1) 
                       {
               total += count;
               output.write(data, 0, count); 
               }
                 output.flush();
                 output.close();
                 input.close();                 

Upvotes: 1

Related Questions