Commons net의 FTP

8489 단어 apacheoraclesql.netqq
최근에 FTP와 관련된 조작을 사용했는데 위대한 개원 커뮤니티가 존재하기 때문에 FTP 프로토콜을 실현할 필요가 없다. 자주 사용하는 FTP 패키지를 봤다. 주로 Apache와 Commonsnet의 Commons FTP와 JDK의 자체 ftp 조작 유형이 있는데 네티즌들이 쓴 예를 보면 비교할 수 있다.나도 모든 프로젝트가 외부 JAR 패키지에 의존하고 싶지 않지만 Commons FTP를 선택했다. 주요 원인은 JDK에서 자체로 가지고 있는 것이 선의 내부 패키지이기 때문에 공개되지 않았고 향후 버전에서 사용할 수 있을 것이라고 보장할 수 없다.사용하기 편리하도록 필요한 기능도 비교적 간단하기 때문에 간단한 포장을 하였다.코드는 다음과 같습니다.
 
package org.migle.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

/**
 * FTP Client   ,   <a href="http://commons.apache.org/net/">Jakarta Commons Net
 * FTPClient</a>         、            ,    Jakarta Commons Net
 * FTPClient         {@link #getFtpclient()}
 *   org.apache.commons.net.ftp.FTPClient
 *   ,  org.apache.commons.net.ftp.FTPClient          <a href =
 * "http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html"
 * > FTPClient API </a>
 * 
 * @since V2.0
 * @version V1.0 2010-2-26
 * @author     
 */
public class FTPClientUtil {

	private static Log logger = LogFactory.getLog(FTPClient.class);

	private FTPClient ftpclient;

	public FTPClientUtil(String host, int port) throws Exception {
		this(host, port, null, null);
	}

	public FTPClientUtil(String host, int port, String username, String password)
			throws Exception {
		ftpclient = new FTPClient();
		try {
			ftpclient.connect(host, port);
			int reply = ftpclient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpclient.disconnect();
				logger.fatal("FTP       ");
				throw new Exception("FTP       ");
			}
			if (username != null) {
				if (!ftpclient.login(username, password)) {
					ftpclient.disconnect();
					logger.fatal("      ,            ");
					throw new Exception("      ,            ");
				}
			}
		} catch (SocketException e) {
			logger.fatal("       FTP   ", e);
			throw new Exception(e);
		} catch (IOException e) {
			logger.fatal("                FTP   ", e);
			throw new Exception(e);
		}
	}

	/**
	 * 
	 * @param path
	 *               FTP       
	 * @param input
	 *               
	 * @throws IOException
	 */
	public boolean upload(String pathname, InputStream input)
			throws IOException {
		//          
		ftpclient.setFileType(FTP.BINARY_FILE_TYPE);
		if (pathname.indexOf("/") != -1) {
			String path = pathname.substring(0, pathname.lastIndexOf("/"));
			mkdir(path);
		}
		return ftpclient.storeFile(new String(pathname.getBytes(), ftpclient.getControlEncoding()), input);
	}

	/**
	 *  FTP      pathname     ,   localName
	 * 
	 * @param pathname
	 * @param localName
	 * @return
	 * @throws Exception
	 */
	public boolean download(String pathname, String localName) throws Exception {
		String filename = localName != null ? localName : pathname
				.substring(pathname.lastIndexOf("/") + 1);

		if (filename == null || filename.isEmpty()) {
			return false;
		}

		//       
		ftpclient.enterLocalPassiveMode();
		//           
		ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

		if (ftpclient.listFiles(new String(pathname.getBytes(),ftpclient.getControlEncoding())).length == 0) {
			logger.fatal("       ");
			throw new Exception("       ");
		}

		File tmp = new File(filename + "_tmp"); //     
		File file = new File(filename);
		FileOutputStream output = null;
		boolean flag;
		try {
			output = new FileOutputStream(tmp);
			flag = ftpclient.retrieveFile(new String(pathname.getBytes(),ftpclient.getControlEncoding()), output);
			output.close();
			if (flag) {
				//     ,       。
				tmp.renameTo(file);
				System.out.println(file.getAbsolutePath());
			}
		} catch (FileNotFoundException e) {
			logger.fatal("      ", e);
			throw new Exception(e);
		} finally {
			output.close();
		}

		return flag;
	}

	/**
	 *      ,             : <code>
	 * 	getFtpclient().removeDirectory(String pathname) 
	 * </code>   
	 * {@link org.apache.commons.net.ftp.FTPClient FTPClient}
	 * 
	 * @param pathname
	 * @return       true,    false(          false)
	 * @throws IOException
	 */
	public boolean delete(String pathname) throws IOException {
		return ftpclient.deleteFile(new String(pathname.getBytes(),ftpclient.getControlEncoding()));
	}

	/**
	 *        pathname,"/"     
	 * 
	 * @param pathname
	 *               
	 * @return        true    false
	 * @throws IOException
	 */
	public boolean changeWorkingDirectory(String pathname) throws IOException {
		return ftpclient.changeWorkingDirectory(new String(pathname.getBytes(),ftpclient.getControlEncoding()));
	}

	/**
	 * @return {@link org.apache.commons.net.ftp.FTPClient FTPClient}  
	 */
	public FTPClient getFtpclient() {
		return this.ftpclient;
	}

	/**
	 * @param ftpclient
	 *            {@link org.apache.commons.net.ftp.FTPClient FTPClient}  
	 */
	public void setFtpclient(FTPClient ftpclient) {
		this.ftpclient = ftpclient;
	}

	public void close() throws Exception {
		ftpclient.disconnect();
	}

	/**
	 * 
	 * @param pathname
	 *                    ,       ,       ("/"  )
	 * @return           true,    false(          false)
	 * @throws IOException
	 */
	public boolean mkdir(String pathname) throws IOException {
		//ftpclient.setControlEncoding("ISO-8859-1");
		//    ,               
		return ftpclient.makeDirectory(new String(pathname.getBytes(),ftpclient.getControlEncoding()));
	}

	public static void main(String[] args) throws Exception {
		// URI uri = new URI(
		// "ftp://100.180.185.205/oracle_10201_database_win32/database/welcome.html");
		// System.out.println(uri.toURL().getHost());
		// System.out.println(uri.toURL().getPath());
		// System.out.println(uri.toURL().getFile());

		FTPClientUtil ftputil = new FTPClientUtil("100.180.185.205", 21, "username",
				"password");
		System.out.println(ftputil.mkdir("  "));
		ftputil.close();
//		ftputil.upload("drop.sql", new FileInputStream("c:/drop.sql"));
//		ftputil.download("/drop.sql", "drop.sql");
		// FTPClient ftp = ftputil.getFtpclient();
		// FTPListParseEngine engine = ftp.initiateListParsing();
		// System.out.println(ftp.listFiles().length);
		// while (engine.hasNext()) {
		// FTPFile[] files = engine.getNext(25); // "page size" you want
		// }

		// FTPClient ftpclient = ftputil.getFtpclient();
		//
		// FTPFile[] f = ftpclient.listFiles("/kk/aa/drop2.sql");
		// System.out.println(f.length);
		// System.out.println(ftpclient.makeDirectory("/tt/aa/bb"));
		// System.out.println(ftpclient.getReplyString());
		// ftpclient.changeWorkingDirectory("/tt/aa/bb");
		//		
		// //System.out.println(ftpclient.deleteFile("/tt/aa/cc/"));
		// System.out.println(ftpclient.getReplyString());
		// ftpclient.changeWorkingDirectory("/");
		// System.out.println(ftpclient.listFiles().length);

//		System.out.println("a".lastIndexOf("/"));
	}
}

좋은 웹페이지 즐겨찾기