FTP / FTPS
Primero hemos de importar la librería commons-net-X.Y.jar que descargaremos desde la web de apache a nuestro proyecto. Si usamos eclipse, botón derecho en el proyecto -> Build Path -> Configure Build Path
En el fichero Java, añadimos los imports necesarios para poder enviar por FTP.
1 2 3 4 |
import org.apache.commons.net.ftp.FTP; // Nos permite indicar si transfer BINARY o ASCII import org.apache.commons.net.ftp.FTPClient; // Para FTP plano import org.apache.commons.net.ftp.FTPSClient; // Para FTPSecure (FTPS) import java.io.FileInputStream; // Abrir y leer el fichero |
Creamos el código para subir el fichero
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
String remote_working_dir_path = "/ruta/remota/del/ftp/"; String local_filepath = "C:/Users/driverlandia/Desktop/commons-net-3.6.jar"; String remote_filename = "commons-net-3.6.jar"; FileInputStream fis = new FileInputStream(local_filepath); FTPClient client = new FTPClient(); try { client.setBufferSize(512); // Opcional para definir Buffer size en bytes client.connect("servidor.ftp.com",21); // no el puerto es por defecto, podemos usar client.connect("servidor.ftp.com"); client.login( props.getProperty("pgi20_ftp_user"), props.getProperty("pgi20_ftp_pass") ); client.enterLocalPassiveMode(); // IMPORTANTE!!!! client.setFileType(FTP.BINARY_FILE_TYPE); client.changeWorkingDirectory(remote_working_dir_path); boolean uploadFile = client.storeFile(remote_filename,fis); client.logout(); client.disconnect(); if ( uploadFile == false ) { throw new Exception("Error al subir el fichero"); } } catch (Exception eFTPClient) { // Gestionar el error, mostrar pantalla, reescalar excepcion... etc... } finally { fis.close(); } |
En caso de ser un servidor FTPS el codigo es exactamente igual, tan solo tendremos que cambiar la linea
FTPClient client = new FTPClient();
por la siguiente
FTPSClient client = new FTPSClient();
La linea marcada como importante en el codigo, tiene su sentido a la pregunta: FTPClient crea fichero con 0 bytes o FTPClient no sube correctamente el fichero independientemente si es un FTP o FTPS. En mi caso este era el problema. Se me creaba el fichero en el FTP, pero no subia el contenido. Además tardaba demasiado a la hora de ejecutar ftp.storeFile.
Fue añadir esta configuración y subía el fichero correctamente y además no tardaba nada.
SFTP
Para subir un fichero a un servidor SFTP, haremos uso de la librería JSCH (jsch-x.y.z.jar) que también deberemos importar en nuestro proyecto.
Descargaremos la class STFPUtils (para no reinventar la rueda) de https://dnhome.wordpress.com/2012/06/25/java-upload-file-to-sftp-server/ y la acomodaremos a nuestro gusto. En mi caso he cambiado el logger por el propio del framework que estoy utilizando.
En nuestro Java haremos uso del siguiente código para subir el fichero.
1 2 3 4 5 6 7 |
SFTPUtils sftp = new SFTPUtils(); sftp.setHostName("sftp.servidor.com"); sftp.setHostPort("22"); sftp.setUserName("usuario"); sftp.setPassWord("password"); sftp.setDestinationDir( remote_working_dir_path ); sftp.uploadFile(local_filepath , remote_filename ); |
Últimos comentarios