0

I have a problem when I want to download file from internet in java. I try to used something like this:

    String stringUrl = "http://imageshack.us/a/img841/7762/formd.png";
    File file = new File("");       
        try {
            URL url = new URL(stringUrl);
            FileUtils.copyURLToFile(url, file);
        }

but I got an I/O exception. What is the best way to download file from internet and put it into 'File' object?

2
  • 1
    You can find your answer from: stackoverflow.com/questions/921262/… Commented Apr 25, 2013 at 12:19
  • ...but beware of the +146 odd first answer to that question that uses the arbitrary 1<<24 value. It'll work fine in this case because it's a simple image, but for most cases where you don't really know or want to guess the file size, I'd just use Long.MAX_VALUE. FWIW, I tihnk this Apache Commons approach is neater. Commented Apr 25, 2013 at 12:29

1 Answer 1

1

That's because you haven't given the file a name, and writing to a file with no name makes no sense.

File file = new File("");  

If you replace that line with something like:

File file = new File("x.png");

...then it should work.

Sign up to request clarification or add additional context in comments.

2 Comments

OMG, That was really easy! Now it works, but what should I do if I don't know an extension of downloaded file? Maybe split my URL string and got this extension? Or is a different and easier way?
You could, but a more reliable way would be to get the content type as detailed here: stackoverflow.com/questions/5801993/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.