`
iehyou
  • 浏览: 132700 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

FTP工具类

    博客分类:
  • J2EE
阅读更多
功能就是将指定文件夹下面的所有文件都上传到FTP上
/**
*上传自定路径的下的文件到FTP
*/
public class FtpTools {

	private String ip = "";

	private String username = "";

	private String password = "";

	private int port = 21;

	private String localFileFullName = "";// 需要上传的目录

	FtpClient ftpClient = null;

	OutputStream os = null;

	FileInputStream is = null;

	public FtpTools(String serverIP, int port, String username, String password) {

		this.ip = serverIP;
		this.username = username;
		this.password = password;
		this.port = port;

	}

	public FtpTools(String serverIP, String username, String password) {

		this.ip = serverIP;
		this.username = username;
		this.password = password;

	}

	/**
	 * 创建文件夹
	 * 
	 * @param dir
	 * @param ftpClient
	 * @throws Exception
	 */
	private void createDir(String dir, FtpClient ftpClient) throws Exception {
		ftpClient.ascii();
		StringTokenizer s = new StringTokenizer(dir, "/"); // sign
		s.countTokens();
		String pathName = "";
		while (s.hasMoreElements()) {
			pathName = pathName + "/" + (String) s.nextElement();
			try {
				ftpClient.sendServer("MKD " + pathName + "\r\n");
			} catch (Exception e) {
				e = null;
			}
			ftpClient.readServerResponse();
		}
		ftpClient.binary();

	}

	/**
	 * 检查文件夹是否存在
	 * 
	 * @param dir
	 * @param ftpClient
	 * @return
	 */
	private boolean isDirExist(String dir, FtpClient ftpClient) {
		try {
			ftpClient.cd(dir);
		} catch (Exception e) {

			return false;
		}
		return true;
	}

	/**
	 * ftp上传
	 * 
	 * @param localFileFullName
	 *            上传的源文件夹
	 * @return
	 */
	public boolean upload(String localFileFullName) {
		this.localFileFullName = localFileFullName;
		try {
			String savefilename = new String(localFileFullName
					.getBytes("ISO-8859-1"), "GBK");
			// 新建一个FTP客户端连接
			ftpClient = new FtpClient();
			ftpClient.openServer(this.ip, this.port);
			ftpClient.login(this.username, this.password);
			
			// 打开本地待长传的文件
			File file_in = new File(savefilename);
			processFile(file_in, ftpClient);
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
			if (ftpClient != null) {
				ftpClient.closeServer();
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("Exception e in Ftp upload(): " + e.toString());
			return false;
		}

	}

	/**
	 * 上传文件
	 * @Deprecated
	 * @param source
	 * @param ftpClient
	 * @throws Exception
	 * 
	 */
	private void processFile(File source, FtpClient ftpClient) throws Exception {
		if (source.exists()) {
			if (source.isDirectory()) {
				if (!isDirExist(source.getPath().substring(localFileFullName.length()).replace('\\', '/'), ftpClient)) {
					createDir(source.getPath().substring(
							localFileFullName.length()).replace('\\', '/'), ftpClient);
				}
				File sourceFile[] = source.listFiles();
				for (int i = 0; i < sourceFile.length; i++) {
					if (sourceFile[i].exists()) {
						if (sourceFile[i].isDirectory()) {
							this.processFile(sourceFile[i], ftpClient);
						} else {
							ftpClient.cd(cheangPath(sourceFile[i].getPath()));
							ftpClient.binary();
							os = ftpClient.put(sourceFile[i].getName());
							byte[] bytes = new byte[1024];
							is = new FileInputStream(sourceFile[i]);
							// 开始复制
							int c;
							// 暂未考虑中途终止的情况
							while ((c = is.read(bytes)) != -1) {
								os.write(bytes, 0, c);
							}
							is.close();
							os.close();
						}
					}
				}
			} else {
				ftpClient.cd(cheangPath(source.getPath()));
				ftpClient.binary();
				os = ftpClient.put(source.getName());
				byte[] bytes = new byte[1024];
				is = new FileInputStream(source);
				// 开始复制
				int c;
				// 暂未考虑中途终止的情况
				while ((c = is.read(bytes)) != -1) {
					os.write(bytes, 0, c);
				}
				is.close();
				os.close();
			}

		} else {
			throw new Exception("此文件或文件夹[" + source.getName() + "]有误或不存在!");
		}

	}

	/**
	 * 获取当前的FTP路径
	 * 
	 * @param path
	 * @return
	 */
	private String cheangPath(String path) {
		path = path.substring(localFileFullName.length()).replace('\\', '/');
		if ("".equals(path)) {
			path = "/";
		} else {
			path = path.substring(0, path.lastIndexOf("/") + 1);
		}
		return path;
	}

}



----------------------------20100426-----------------------------
今天换了FTP  不知道什么原因上面的代码不能用了 ,差了很久 还是有问题,郁闷....
对FTP协议也还是不是很了解,后来换了Apache的FTP组件,就可以了....
package com.wasu.itv.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.StringTokenizer;

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;

public class FtpTools {
	private static Log log = LogFactory.getLog(FtpTools.class);

	private FTPClient ftpClient = null;

	private String ip = "";

	private String username = "itvFtp";

	private String password = "itv";

	private int port = 21;

	private String localFileFullName = "";// 需要上传的目录

	public FtpTools(String serverIP, int port, String username, String password) {
		this.ip = serverIP;
		this.username = username;
		this.password = password;
		this.port = port;
		this.loginFtp();
	}

	public boolean loginFtp() {
		boolean flag = true;
		if (ftpClient == null) {
			int reply;
			try {
				ftpClient = new FTPClient();
				ftpClient.setControlEncoding("GBK");
				ftpClient.connect(ip);
				ftpClient.login(username, password);
				ftpClient.setDefaultPort(port);
				reply = ftpClient.getReplyCode();
				ftpClient.setDataTimeout(120000);
			} catch (SocketException e) {
				flag = false;
				e.printStackTrace();
				System.err.println("登录ftp服务器失败,连接超时!");
				log.debug("登录ftp服务器失败");
			} catch (IOException e) {
				flag = false;
				e.printStackTrace();
				System.err.println("登录ftp服务器失败,FTP服务器无法打开!");
				log.debug("登录ftp服务器失败");
			}

		}
		return flag;

	}
	public boolean logoutFtp() {
		try {
			if (ftpClient != null) {
				ftpClient.logout();
				ftpClient.disconnect();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	
	
	public String getUploadPath(String path){
		File source = new File(path);
		return source.getPath().substring(
				localFileFullName.length()).replace('\\', '/');
	}
	/**
	 * 输出到文件
	 * 
	 * @param fileName
	 * @param data
	 * @throws Exception 
	 */
	public boolean upload(String fileName) throws Exception {
		boolean flag = true;
		File source = new File(fileName);
		if (source.exists()) {
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
			if (source.isDirectory()) {
				if (!isDirExist(source.getPath().substring(localFileFullName.length()).replace('\\', '/'))) {
					createDir(source.getPath().substring(localFileFullName.length()).replace('\\', '/'));
				}
				File sourceFile[] = source.listFiles();
				for (int i = 0; i < sourceFile.length; i++) {
					if (sourceFile[i].exists()) {
						if (sourceFile[i].isDirectory()) {
							this.upload(sourceFile[i].getCanonicalPath());
						} else {
							//改变目录
							this.changerToPath(sourceFile[i].getCanonicalPath());
							flag = ftpClient.storeFile(sourceFile[i].getName(), new FileInputStream(sourceFile[i]));
							log.debug("文件:"+sourceFile[i].getName()+"上传"+(flag==true?"成功":"失败"));
							//返回根目录
							ftpClient.changeWorkingDirectory("~");
						}
					}
				}
			}else {
				try {
					FileInputStream bis = new FileInputStream(source);
					this.changerToPath(source.getCanonicalPath());
					flag = ftpClient.storeFile(source.getName(), bis);
					log.debug("文件:"+source.getName()+"上传"+(flag==true?"成功":"失败"));
					ftpClient.changeWorkingDirectory("~");
					bis.close();
				}  catch (Exception e) {
					e.printStackTrace();
					log.debug("本地文件上传失败!"+source.getCanonicalPath(), e);
				}
			}
		}
		return flag;
	}
		
	/**
		 * 获取当前的FTP路径
		 * 
		 * @param path
		 * @return
		 */
	private boolean changerToPath(String path) {
		boolean isOK = false;
		path = path.substring(localFileFullName.length()).replace('\\', '/');
		StringTokenizer s = new StringTokenizer(path, "/"); 
		s.countTokens();
		String pathName = "";
		while (s.hasMoreElements()) {
			pathName = (String) s.nextElement();
			try {
				isOK=ftpClient.changeWorkingDirectory(pathName);
			} catch (Exception e) {
				e = null;
				isOK=false;
			}
		}
		return isOK;
	}

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		FtpTools packer = new FtpTools("125.200.222.164",21,"itvFtp","itv");
		packer.localFileFullName="E:\\biyatech\\washu\\SMSP\\itv\\src\\com\\wasu";
		packer.upload("E:\\biyatech\\washu\\SMSP\\itv\\src\\com\\wasu");
		packer.logoutFtp();
	}

	/**
	 * 创建文件夹
	 * 
	 * @param dir
	 * @param ftpClient
	 * @throws Exception
	 */
	private void createDir(String dir) throws Exception {
		StringTokenizer s = new StringTokenizer(dir, "/"); 
		s.countTokens();
		String pathName = "";
		while (s.hasMoreElements()) {
			pathName = (String) s.nextElement();
			try {
				ftpClient.makeDirectory(pathName);
				ftpClient.changeWorkingDirectory(pathName);
			} catch (Exception e) {
				e = null;
			}
		}
		ftpClient.changeWorkingDirectory("~");
	}

	/**
	 * 检查文件夹是否存在
	 * 
	 * @param dir
	 * @param ftpClient
	 * @return
	 */
	private boolean isDirExist(String dir) {
		boolean isDirExist = false;
		try {
			isDirExist = ftpClient.changeWorkingDirectory(dir);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return isDirExist;
	}
	

	public void setLocalFileFullName(String localFileFullName) {
		this.localFileFullName = localFileFullName;
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics