天天看点

org.apache.commons.net.ftp.FTPClient

package classTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

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





public class FtpOperate {
	private FTPClient client = new FTPClient();
	
	/**
	 * 登录FTP,并返回登录是否成功的Boolean值
	 * @param host
	 * @param port
	 * @param user
	 * @param password
	 * @return
	 */
	public boolean login(String host, int port, String user, String password) {
		boolean flag = true;
		try {
                        //防止乱码,且设置编码方式必须在连接ftp之前
			client.setControlEncoding("GBK");
			client.connect("192.168.19.190", 10086);
			client.login("zqz", "123456");
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}
	/**
	 * 关闭FTP连接
	 */
	public void close() {
		if(client.isConnected()) {
			try {
				client.disconnect();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 在父级节点创建子节点目录,如果父级节点为根节点parent可以为空或“/”
	 * @param parent
	 * @param path
	 * @return
	 */
	public boolean makeDir(String parent, String path) {
		boolean flag = true;
		flag = cdAssignPath(parent);
		if(flag) {
			try {
				//创建已经存在的目录会报错
				client.makeDirectory(path);
			}catch (Exception e) {
				e.printStackTrace();
				flag = false;
			}
		}
		return flag;
	}
	
	/**
	 * 上传文件
	 * @param path保存FTP位置
	 * @param file要上传的文件
	 * @param remoteName在FTP保存时的名字
	 */
	public void upload(String path, File file, String remoteName) {
		try {
			if(cdAssignPath(path)) {
				System.out.println("==");
				client.storeFile(remoteName, new FileInputStream(file));
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 下载文件
	 * @param remotePath
	 * @param remoteName
	 * @param localPath
	 * @param localName
	 */
	public void download(String remotePath, String remoteName, String localPath, String localName) {
		if(cdAssignPath(remotePath)) {
			try {
				File file = new File(localPath);
				if(!file.exists()) {
					file.mkdirs();
				}
				FileOutputStream write = new FileOutputStream(new File(localPath + "/" + localName));
				client.retrieveFile(remoteName, write);
				write.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取指定路径下的文件列表
	 * @param path
	 * @return
	 */
	public String[] ls(String path) {
		if(cdAssignPath(path)) {
			try {
				return client.listNames();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 切换当前目录到指定路径,该路径必须从根路径("/")开始
	 * @param path
	 * @return
	 */
	public boolean cdAssignPath(String path) {
		boolean flag = true;
		try {
			client.changeWorkingDirectory(path);
		} catch (IOException e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}
}