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

前端 未结 21 3335
情深已故
情深已故 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:29

    This is another java7 variant based on Brian Risk's answer with usage of try-with statement:

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

提交回复
热议问题