Exemplo n.º 1
0
  public void uploadFile(String filePath, byte[] data) throws IOException {
    login();

    OutputStream os = ftpClient.storeFileStream(filePath);
    int ftpUploadReplyCode = ftpClient.getReplyCode();

    if (FTPReply.isNegativePermanent(ftpUploadReplyCode)) {
      throw new IOException("SERVER FTP:REQUEST DENIED");
    } else if (FTPReply.isNegativeTransient(ftpUploadReplyCode)) {
      uploadFile(filePath, data);
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    IOUtils.copy(bais, os);

    bais.close();
    os.flush();
    os.close();

    if (!ftpClient.completePendingCommand()) {
      uploadFile(filePath, data);
    }

    logout();
  }
Exemplo n.º 2
0
  /**
   * Method that downloads a file from the FTP server.
   *
   * @param filepath is the absolute path of the file in the FTP server
   * @return the file content as byte[]
   * @throws IOException if an i/o error occurs.
   */
  public byte[] downloadFile(String filepath) throws IOException {
    login();

    FTPFile ftpFile = ftpClient.listFiles(filepath)[0];

    // file exists on FTP server?
    if (ftpFile == null) {
      throw new IOException("NULL FILE POINTER IN THE FTP SERVER");
    }

    // file is a directory?
    if (ftpFile.isDirectory()) {
      throw new IOException("FILE POINTER IS A DIRECTORY");
    }

    // its a file and exists. start download stream...
    InputStream is = ftpClient.retrieveFileStream(filepath);

    // how the server replied to the fetch command?
    int ftpReplyCode = ftpClient.getReplyCode();

    // denied?
    if (FTPReply.isNegativePermanent(ftpReplyCode)) {
      throw new IOException("SERVER FTP:REQUEST DENIED");

      // can we try again?
    } else if (FTPReply.isNegativeTransient(ftpReplyCode)) {
      // close the already open stream before try again...
      if (is != null) {
        is.close();
      }
      return downloadFile(filepath);
    }

    // server accepted the command
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // copying the file
    IOUtils.copy(is, baos);

    // closing open streams
    is.close();
    baos.flush();
    baos.close();

    // transaction is successful?
    boolean transactionCompleted = ftpClient.completePendingCommand();
    if (!transactionCompleted) {
      return downloadFile(filepath);
    }

    // we got the file
    logout();
    return baos.toByteArray();
  }