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

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

    When using Java 7+ use the following method to download a file from the Internet and save it to some directory:

    private static Path download(String sourceURL, String targetDirectory) throws IOException
    {
        URL url = new URL(sourceURL);
        String fileName = sourceURL.substring(sourceURL.lastIndexOf('/') + 1, sourceURL.length());
        Path targetPath = new File(targetDirectory + File.separator + fileName).toPath();
        Files.copy(url.openStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
    
        return targetPath;
    }
    

    Documentation here.

提交回复
热议问题