Solved

Downloading image

Posted on 2003-11-24
4
244 Views
Last Modified: 2012-05-04
Hi!

I am trying to write a function that download image from url to my computer’s specific local directory.
This is a command-line application. Please show me an example.

Thanks,

0
Comment
Question by:dkim18
  • 3
4 Comments
 
LVL 92

Accepted Solution

by:
objects earned 250 total points
ID: 9814893
URL url = new URL(text);
URLConnection urlConnection = url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream file = new FileOutputStream(filename);

int len;
byte[] buf = new byte[256];
while ((len = is.read(buf))>=0)
{
  file.write(buf, 0, len);
}
is.close();
file.close();
0
 

Author Comment

by:dkim18
ID: 9845178
I read  API for java.io.InputStream read(byte[]) method and java.io.FileOutputStream write(byte[], int off, int len).
The read(byte[]) method returns an integer that tells me how many bytes were actually read in. So, I think I should only write that many bytes out. Doesn't your code above only work if the incoming file's byte count is evenly divisible by 256?
0
 
LVL 92

Expert Comment

by:objects
ID: 9846430
the code above does only write the number of bytes read, where len is the number of bytes:

file.write(buf, 0, len);

0
 
LVL 92

Expert Comment

by:objects
ID: 9893343
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question