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?

caro2
  • 155
  • 1
  • 4
  • 13
  • 1
    You can find your answer from: http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java – Navand Apr 25 '13 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. – Michael Berry Apr 25 '13 at 12:29

1 Answers1

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.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • 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? – caro2 Apr 28 '13 at 13:04
  • You could, but a more reliable way would be to get the content type as detailed here: http://stackoverflow.com/questions/5801993/quickest-way-to-get-content-type – Michael Berry Apr 28 '13 at 15:42