Solved

Downloading image

Posted on 2003-11-24
4
251 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

840 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