title: Uploading files in spring boot without replacing existing files and moving existing to another directory by versioning them
body: <p>I need to upload files and download files in different directories, but I don't want to replace them. Instead the existing file with the same name should be renamed by appending version number and moved to another directory. I have searched several examples but couldn't find the similar one.</p>
  <p><strong>Here is my store file service</strong></p>
  <pre><code>public String storeFile(MultipartFile file) {
  
          String fileName = StringUtils.cleanPath(file.getOriginalFilename());
  
          try {
  
              if (fileName.contains(&quot;..&quot;)) {
                  throw new FileStorageException(&quot;Sorry! Filename contains invalid path sequence &quot; + fileName);
              }
  
              Path targetLocation;
  
              String extensionType = FilenameUtils.getExtension(fileName);
  
              switch (extensionType) {
  
                  case &quot;zip&quot;:
                      targetLocation = this.zipFileStorageLocation.resolve(fileName);
                      break;
                  case &quot;json&quot;:
                      targetLocation = this.jsonFileStorageLocation.resolve(fileName);
                      break;
                  default:
                      targetLocation = this.fileStorageLocation.resolve(fileName);
                      break;
  
              }
  
              Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
  
              return fileName;
  
          } catch (IOException ex) {
              logger.debug(&quot;Could not store file &quot; + fileName + &quot;. Please try again!&quot;, ex);
              throw new FileStorageException(&quot;Could not store file &quot; + fileName + &quot;. Please try again!&quot;, ex);
          }
      }
  </code></pre>
  <p>I thought to write the function which moves the existing file to another directory, but then the problem is with the version number, before renaming the existing file, I need to know what version exists, so that I can rename with next version number. Which I think I should check with sub string of file name exists in the versions directory or not, to know what version exists if it is. But I don't know how to implement this, can someone suggest me the things that you think would work for me please ?</p>