ftp之创建目录

最近在做ftp上传下载相关的一些东西,下面来记录并分享下通过ftp客户端创建目录的实现:

因需要创建多级目录,但是ftp客户端只能创建单级目录,下面稍微做了一个完善:

package test;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
/**
 * 
 * @author wangxueying
 *
 */
public class Test {
	public static void main(String[] args) {
		String host = "127.0.0.0";
		int port = 21;
		String userName = "test";
		String password = "123456";
		String path = "/work/project/test/down/content";
		//分割路径
		List list = getPathList(path);
		try {
			FTPClient ftp = new FTPClient();
			//基本设置
			ftp.setDefaultTimeout(20000);
			ftp.setDataTimeout(3600000);
			ftp.setConnectTimeout(60000);
			ftp.connect(host, port);
			ftp.login(userName, password);
			ftp.setBufferSize(4096);
			ftp.setKeepAlive(true);
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.enterLocalPassiveMode();
			//循环遍历创建路径
			for(int i=0; i " + list.get(i));
						close(ftp);
						return;
					}
				}
			}
			System.out.println(ftp.isConnected());//查看ftp是否已连接
			System.out.println(ftp.changeWorkingDirectory(path));//查看目录是否已存在
			close(ftp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//分割路径
	public static List getPathList(String path){
		String[] dirs = path.split("/");
		List list = new ArrayList<>();
		String pathname = "";
		for(String str : dirs){
			if(StringUtils.isEmpty(str)){
				continue;
			}
			pathname = pathname + "/" + str;
			list.add(pathname);
		}
		return list;
	}
	//关闭ftp
	public static void close(FTPClient ftp){
		try {
			if(ftp.isConnected()){
				ftp.logout();
				ftp.disconnect();
			}
			ftp = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(FTP)