How to download and save a file from Internet using Java?

前端 未结 21 3319
情深已故
情深已故 2020-11-21 05:06

There is an online file (such as http://www.example.com/information.asp) I need to grab and save to a directory. I know there are several methods for grabbing a

21条回答
  •  醉梦人生
    2020-11-21 05:46

    This answer is almost exactly like selected answer but with two enhancements: it's a method and it closes out the FileOutputStream object:

        public static void downloadFileFromURL(String urlString, File destination) {    
            try {
                URL website = new URL(urlString);
                ReadableByteChannel rbc;
                rbc = Channels.newChannel(website.openStream());
                FileOutputStream fos = new FileOutputStream(destination);
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                fos.close();
                rbc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    

提交回复
热议问题