ftp4j 에서 http 프 록 시 사용

11920 단어 Java
Ftp4j 는 비교적 쓰기 좋 고 각종 대 리 를 지원 합 니 다.
명령 행 을 통 해 프 록 시 를 통 해 원 격 서버 에 디 렉 터 리 를 업로드 하고 스케줄 링 작업 에 가입 할 수 있 는 경우 자바 를 직접 쓰 는 것 이 좋 습 니 다.
filezilla 도형 화 된 클 라 이언 트 는 프 록 시,디 렉 터 리 업 로드 를 지원 하지만 스케줄 링 은 지원 되 지 않 습 니 다.
winscp 명령 행 은 디 렉 터 리 업로드 가 지원 되 지만 프 록 시 는 지원 되 지 않 습 니 다.
curl 은 프 록 시 를 지원 하지만 디 렉 터 리 업로드 가 지원 되 지 않 습 니 다.
다른 ftp 명령 행 은 더 약 한 닭 입 니 다.
그래서 스스로 자바 를 만들어 서 먹고 입 는 것 이 풍족 하 다.말 이 많 지 않 습 니 다.다음 코드 는 comons-lang-2.6.jar,ftp4j-1.7.2.jar 테스트 를 통 과 했 습 니 다.http://www.sauronsoftware.it/projects/ftp4j/download.php

import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;

import org.apache.commons.lang.StringUtils;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPFile;
import it.sauronsoftware.ftp4j.connectors.HTTPTunnelConnector;


/**
 * FTP       
 * 
 * @author Johnson
 * @version Tuesday December 28th, 2010
 */
public class FTPUtils {

	private static FTPUtils ftp;
	/**
	 * FTP    
	 */
	private static String ADDRESS = "ftp://106.106.106.106";
	/**
	 * FTP     
	 */
	private static String USERNAME = "xxxuser";
	/**
	 * FTP    
	 */
	private static String PASSWORD = "123456";

	/**
	 *     
	 */
	protected FTPUtils() {
	}

	/**
	 *      
	 * 
	 * @return
	 */
	public static FTPUtils getInstance() {
		if (ftp == null) {
			ftp = new FTPUtils();
		}
		return ftp;
	}

	/**
	 *   FTP     
	 * 
	 * @return
	 * @throws Exception
	 */
	public FTPClient getClient() throws Exception {
		FTPClient client = new FTPClient();
		
		HTTPTunnelConnector httpProxy = new HTTPTunnelConnector("http.myproxy.com", 8080);		
		client.setConnector(httpProxy);
		
		client.setCharset("utf-8");
		client.setType(FTPClient.TYPE_BINARY);
		URL url = new URL(FTPUtils.ADDRESS);
		//int port = url.getPort() < 1 ? 21 : url.getPort();
		int port = 8899;
		System.out.println("----Login to Ftp server:" + url.toString() + ":" + port);
		client.connect(url.getHost(), port);
		client.login(FTPUtils.USERNAME, FTPUtils.PASSWORD);
		return client;
	}

	/**
	 *        
	 * 
	 * @param client FTP     
	 * @throws Exception
	 */
	private void logout(FTPClient client) throws Exception {
		if (client != null) {
			try {
				//   FTP         ,        
				client.logout(); //     
			} catch (FTPException fe) {
			} catch (Exception e) {
				throw e;
			} finally {
				if (client.isConnected()) { //     
					client.disconnect(true);
				}
			}
		}
	}

	/**
	 *     
	 * 
	 * @param client FTP     
	 * @param dir      
	 * @throws Exception
	 */
	private void mkdirs(FTPClient client, String dir) throws Exception {
		if (dir == null) {
			return;
		}
		dir = dir.replace("//", "/");
		String[] dirs = dir.split("/");
		for (int i = 0; i < dirs.length; i++) {
			dir = dirs[i];
			if (!StringUtils.isEmpty(dir)) {
				if (!exists(client, dir)) {
					client.createDirectory(dir);
				}
				client.changeDirectory(dir);
			}
		}
	}

	/**
	 *   FTP  
	 * 
	 * @param url  FTP  
	 * @param dir   
	 * @return
	 * @throws Exception
	 */
	private URL getURL(URL url, String dir) throws Exception {
		String path = url.getPath();
		if (!path.endsWith("/") && !path.endsWith("//")) {
			path += "/";
		}
		dir = dir.replace("//", "/");
		if (dir.startsWith("/")) {
			dir = dir.substring(1);
		}
		path += dir;
		return new URL(url, path);
	}

	/**
	 *   FTP  
	 * 
	 * @param dir   
	 * @return
	 * @throws Exception
	 */
	private URL getURL(String dir) throws Exception {
		return getURL(new URL(FTPUtils.ADDRESS), dir);
	}

	/**
	 *            
	 * 
	 * @param client FTP     
	 * @param dir         
	 * @return
	 * @throws Exception
	 */
	private boolean exists(FTPClient client, String dir) throws Exception {
		return getFileType(client, dir) != -1;
	}

	/**
	 *            
	 * 
	 * @param client FTP     
	 * @param dir         
	 * @return -1、         0、   1、  
	 * @throws Exception
	 */
	private int getFileType(FTPClient client, String dir) throws Exception {
		FTPFile[] files = null;
		try {
			files = client.list(dir);
		} catch (Exception e) {
			return -1;
		}
		if (files.length > 1) {
			return FTPFile.TYPE_DIRECTORY;
		} else if (files.length == 1) {
			FTPFile f = files[0];
			if (f.getType() == FTPFile.TYPE_DIRECTORY) {
				return FTPFile.TYPE_DIRECTORY;
			}
			String path = dir + "/" + f.getName();
			try {
				int len = client.list(path).length;
				if (len == 1) {
					return FTPFile.TYPE_DIRECTORY;
				} else {
					return FTPFile.TYPE_FILE;
				}
			} catch (Exception e) {
				return FTPFile.TYPE_FILE;
			}
		} else {
			try {
				client.changeDirectory(dir);
				client.changeDirectoryUp();
				return FTPFile.TYPE_DIRECTORY;
			} catch (Exception e) {
				return -1;
			}
		}
	}

	/**
	 *        
	 * 
	 * @param dir      
	 * @param del         ,   false
	 * @param file          
	 * @throws Exception
	 */
	public void upload(String dir, boolean del, File... files) throws Exception {
		if (StringUtils.isEmpty(dir)) {
			return;
		}
		FTPClient client = null;
		try {
			client = getClient();
			mkdirs(client, dir); //     
			for (File file : files) {
				if (file.isDirectory()) { //     
					uploadFolder(client, getURL(dir), file, del);
				} else {
					client.upload(file); //     
					if (del) { //      
						file.delete();
					}
				}
			}
		} finally {
			logout(client);
		}
	}

	/**
	 *        
	 * 
	 * @param dir       
	 * @param files          
	 * @throws Exception
	 */
	public void upload(String dir, File... files) throws Exception {
		upload(dir, false, files);
	}

	/**
	 *        
	 * 
	 * @param dir      
	 * @param del         ,   false
	 * @param path          
	 * @throws Exception
	 */
	public void upload(String dir, boolean del, String... paths) throws Exception {
		if ( paths.length<= 0) {
			return;
		}
		File[] files = new File[paths.length];
		for (int i = 0; i < paths.length; i++) {
			files[i] = new File(paths[i]);
		}
		upload(dir, del, files);
	}

	/**
	 *        
	 * 
	 * @param dir       
	 * @param paths          
	 * @throws Exception
	 */
	public void upload(String dir, String... paths) throws Exception {
		upload(dir, false, paths);
	}

	/**
	 *     
	 * 
	 * @param client    FTP     
	 * @param parentUrl    URL
	 * @param file        
	 * @throws Exception
	 */
	public void uploadFolder(FTPClient client, URL parentUrl, File file, boolean del) throws Exception {
		client.changeDirectory(parentUrl.getPath());
		String dir = file.getName(); //       
		URL url = getURL(parentUrl, dir);
		if (!exists(client, url.getPath())) { //           
			client.createDirectory(dir); //     
		}
		client.changeDirectory(dir);
		File[] files = file.listFiles(); //               
		for (int i = 0; i < files.length; i++) {
			file = files[i];
			if (file.isDirectory()) { //      ,     
				uploadFolder(client, url, file, del);
			} else { //      ,    
				client.changeDirectory(url.getPath());
				client.upload(file);
				if (del) { //      
					file.delete();
				}
				System.out.println("uploading... " + file.getAbsolutePath());
			}
		}
	}

	/**
	 *        
	 * 
	 * @param dir        
	 * @throws Exception
	 */
	public void delete(String... dirs) throws Exception {
		if (dirs.length<= 0) {
			return;
		}
		FTPClient client = null;
		try {
			client = getClient();
			int type = -1;
			for (String dir : dirs) {
				client.changeDirectory("/"); //       
				type = getFileType(client, dir); //       
				if (type == 0) { //     
					client.deleteFile(dir);
				} else if (type == 1) { //     
					deleteFolder(client, getURL(dir));
				}
			}
		} finally {
			logout(client);
		}
	}

	/**
	 *     
	 * 
	 * @param client FTP     
	 * @param url    FTP URL
	 * @throws Exception
	 */
	private void deleteFolder(FTPClient client, URL url) throws Exception {
		String path = url.getPath();
		client.changeDirectory(path);
		FTPFile[] files = client.list();
		String name = null;
		for (FTPFile file : files) {
			name = file.getName();
			//       
			if (".".equals(name) || "..".equals(name)) {
				continue;
			}
			if (file.getType() == FTPFile.TYPE_DIRECTORY) { //        
				deleteFolder(client, getURL(url, file.getName()));
			} else if (file.getType() == FTPFile.TYPE_FILE) { //     
				client.deleteFile(file.getName());
			}
		}
		client.changeDirectoryUp();
		client.deleteDirectory(url.getPath()); //       
	}

	/**
	 *        
	 * 
	 * @param localDir       
	 * @param dirs           
	 * @throws Exception
	 */
	public void download(String localDir, String... dirs) throws Exception {
		if (dirs.length<= 0 ) {
			return;
		}
		FTPClient client = null;
		try {
			client = getClient();
			File folder = new File(localDir);
			if (!folder.exists()) { //           ,   
				folder.mkdirs();
			}
			int type = -1;
			String localPath = null;
			for (String dir : dirs) {
				client.changeDirectory("/"); //       
				type = getFileType(client, dir); //       
				if (type == 0) { //   
					localPath = localDir + "/" + new File(dir).getName();
					client.download(dir, new File(localPath));
				} else if (type == 1) { //   
					downloadFolder(client, getURL(dir), localDir);
				}
			}
		} finally {
			logout(client);
		}
	}

	/**
	 *      
	 * 
	 * @param client   FTP     
	 * @param url      FTP URL
	 * @param localDir       
	 * @throws Exception
	 */
	private void downloadFolder(FTPClient client, URL url, String localDir) throws Exception {
		String path = url.getPath();
		client.changeDirectory(path);
		//              
		File folder = new File(localDir + "/" + new File(path).getName());
		if (!folder.exists()) {
			folder.mkdirs();
		}
		localDir = folder.getAbsolutePath();
		FTPFile[] files = client.list();
		String name = null;
		for (FTPFile file : files) {
			name = file.getName();
			//       
			if (".".equals(name) || "..".equals(name)) {
				continue;
			}
			if (file.getType() == FTPFile.TYPE_DIRECTORY) { //        
				downloadFolder(client, getURL(url, file.getName()), localDir);
			} else if (file.getType() == FTPFile.TYPE_FILE) { //     
				client.download(name, new File(localDir + "/" + name));
			}
		}
		client.changeDirectoryUp();
	}

	/**
	 *          
	 * 
	 * @param dir   
	 * @return
	 * @throws Exception
	 */
	public String[] list(String dir) throws Exception {
		FTPClient client = null;
		try {
			client = getClient();
			client.changeDirectory(dir);
			String[] values = client.listNames();
			if (values != null) {
				//      (     )
				Arrays.sort(values, new Comparator() {
					public int compare(String val1, String val2) {
						return val1.compareToIgnoreCase(val2);
					}
				});
			}
			return values;
		} catch (FTPException fe) {
			//            
			String mark = "code=550";
			if (fe.toString().indexOf(mark) == -1) {
				throw fe;
			}
		} finally {
			logout(client);
		}
		return new String[0];
	}
}
import java.io.File;
import java.net.URL;

/**
 */
public class CopyDIST {

	public static void main(String[] args) {

		System.out.println("***************************************************************************
"); //CopyDIST copyDIST = new CopyDIST(); FTPUtils ftp4jUtil = new FTPUtils(); String srcDirName = args[0]; //String srcDestName = args[2]; try { String dest = "ftp://106.106.106.106:8899/ant-design-vue-jeecg/"; URL parentUrl = new URL(dest); ftp4jUtil.uploadFolder(ftp4jUtil.getClient(),parentUrl,new File(srcDirName),false); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println("dirName=" +dirName); } }

좋은 웹페이지 즐겨찾기