Subir un archivo a un servidor FTP usando sockets

Salida
=====================================================================
220———- Welcome to Pure-FTPd [privsep] [TLS] ———-
220-You are user number 62 of 500 allowed.
220-Local time is now 00:29. Server port: 21.
220-This is a private system – No anonymous login
220-IPv6 connections are also welcome on this server.
220 You will be disconnected after 2 minutes of inactivity.
331 User **** OK. Password required
230-User **** has group access to: vhosts
230-OK. Current restricted directory is /
230 7846 Kbytes used (0%) – authorized: 6144000 Kb
250 OK. Current directory is /test
200 TYPE is now ASCII
227 Entering Passive Mode (67,220,217,230,134,37)
150 Accepted data connection
uploading file…
File sucessfully transferred!

=====================================================================

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.util.StringTokenizer;
/**
 *@author Leyer 
 */
public class ftp {
	/**
	 * Sube un archivo a un servidor FTP
	 * 
	 * @param ftpServer Servidor FTP
	 * @param user      Usuario
	 * @param password  Contraseña
	 * @param location  Directorio donde se subira el archivo
	 * @param file      Archivo que se va a subir
	 * @param debug     Para Mostrar las respuestas del servidor
	 * 
	 */
	public static void uploadFileToFTP(String ftpServer,String user,String password,String location,File file, boolean debug     ){
		try {
		if(file.exists()){
			Socket socket=new Socket(ftpServer,21);
			BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
			bufferedWriter.write("USER "+user+"\r\n");
			bufferedWriter.flush();
			bufferedWriter.write("PASS "+password+"\r\n");
			bufferedWriter.flush();
			bufferedWriter.write("CWD "+location+"\r\n");
			bufferedWriter.flush();
			bufferedWriter.write("TYPE A\r\n");
			bufferedWriter.flush();
			bufferedWriter.write("PASV\r\n");
			bufferedWriter.flush();
			String response=null;
			while((response=bufferedReader.readLine())!=null){
				if(debug)
					System.out.println(response);
				if(response.startsWith("530")){
					System.err.println("Login aunthentication failed");
					break;
				}
				if(response.startsWith("227")){
					    String address = null;  
		                int port = -1;  
		                int opening = response.indexOf('(');  
		                int closing = response.indexOf(')', opening + 1);  
		                if (closing > 0) {  
		                    String dataLink = response.substring(opening + 1, closing);  
		                    StringTokenizer tokenizer = new StringTokenizer(dataLink, ",");  
		                    try {  
		                        address = tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken();  
		                        port = Integer.parseInt(tokenizer.nextToken()) * 256 + Integer.parseInt(tokenizer.nextToken());  
		                    }  
		                    catch (Exception e) {  
		                        e.printStackTrace();
		                    }
		                    try{
				            Socket transfer =new Socket(address,port);
		        			bufferedWriter.write("STOR "+file.getName()+"\r\n");
		        			bufferedWriter.flush();
		        	        response=bufferedReader.readLine();
		        	        if(debug)
		        	        	System.out.println(response);
		        			if(response.startsWith("150")){
				        		FileInputStream fileInputStream=new FileInputStream(file);
				        		final int BUFFER_SIZE=1024;
				        		byte buffer[]=new byte[BUFFER_SIZE];
				        		int len=0,off=0;
				        		if(debug)
				        			System.out.println("uploading file...");
				        		while((len=fileInputStream.read(buffer))!=-1)
				        			transfer.getOutputStream().write(buffer, off, len);
				        		transfer.getOutputStream().flush();
				        		transfer.close();
				        		bufferedWriter.write("QUIT\r\n");
				        		bufferedWriter.flush();
				        		bufferedReader.close();
				        		socket.close();
				        		System.out.println("File sucessfully transferred!");
			        			break;
		        				}
		                    }catch (Exception e) {
								System.err.println(e);
							}
		                }  
					}
				}
			}else{
				System.err.println(file+"no exist!");
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		uploadFileToFTP("***.net","*******","*******","/test", new File("c:\\readme.txt"),true);
	}
}

Anuncios

One Comment to “Subir un archivo a un servidor FTP usando sockets”

  1. Thanks… After trying with a bunch of different routines and jars, this is the only one that was useful. Maybe because we are also connecting to PureFTP

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

A %d blogueros les gusta esto: