Hello! There is a task: download the file by reference to a temporary folder, then move this file to the specified folder.

Here is the code for the working method:

public static Path downloadFile(String urlString, Path downloadDirectory) throws IOException { // implement this method URL url = new URL(urlString); String filename = urlString.substring(urlString.lastIndexOf('/') + 1, urlString.lastIndexOf('.')); String suffix = urlString.substring(urlString.lastIndexOf('.')); InputStream inputStream = url.openStream(); Path tempFile = Files.createTempFile(filename,suffix); Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING); Path target = Paths.get(downloadDirectory + "/" + filename + suffix); Files.move(tempFile, target); return target; } 

Question: why, if StandardCopyOption.REPLACE_EXISTING removed from the Files.copy method, a Files.copy exception is FileAlreadyExistsException if I try to copy a file from the stream to the newly created one, which means an empty temporary file?

    1 answer 1

    into the newly created, which means an empty temporary file

    The Files.copy created file is indeed empty, but for the Files.copy method, Files.copy does not matter whether the file is empty or not, it is only important whether the file exists or not. From the documentation for the method:

    By default

    what can be translated as

    By default, the copy operation fails if the file exists