protected void copyFileToLocalDirectory(
      String remoteDirectoryPath, F remoteFile, File localDirectory, Session<F> session)
      throws IOException {
    String remoteFileName = this.getFilename(remoteFile);
    String localFileName = this.generateLocalFileName(remoteFileName);
    String remoteFilePath =
        remoteDirectoryPath != null
            ? (remoteDirectoryPath + this.remoteFileSeparator + remoteFileName)
            : remoteFileName;
    if (!this.isFile(remoteFile)) {
      if (this.logger.isDebugEnabled()) {
        this.logger.debug("cannot copy, not a file: " + remoteFilePath);
      }
      return;
    }

    File localFile = new File(localDirectory, localFileName);
    if (!localFile.exists()) {
      String tempFileName = localFile.getAbsolutePath() + this.temporaryFileSuffix;
      File tempFile = new File(tempFileName);
      OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tempFile));
      try {
        session.read(remoteFilePath, outputStream);
      } catch (Exception e) {
        if (e instanceof RuntimeException) {
          throw (RuntimeException) e;
        } else {
          throw new MessagingException(
              "Failure occurred while copying from remote to local directory", e);
        }
      } finally {
        try {
          outputStream.close();
        } catch (Exception ignored2) {
        }
      }

      if (tempFile.renameTo(localFile)) {
        if (this.deleteRemoteFiles) {
          session.remove(remoteFilePath);
          if (this.logger.isDebugEnabled()) {
            this.logger.debug("deleted " + remoteFilePath);
          }
        }
      }
      if (this.preserveTimestamp) {
        localFile.setLastModified(getModified(remoteFile));
      }
    }
  }