package classTest;
import it.sauronsoftware.ftp4j.FTPClient;
import java.io.File;
public class FtpHandle {
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 {
client.connect(host, port);
client.login(user, password);
//数据传输方式
client.setType(FTPClient.TYPE_BINARY);
client.setCharset("GBK");
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
return flag;
}
/**
* 关闭FTP连接
*/
public void close() {
if(client.isConnected()) {
try {
client.disconnect(false);
} 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.createDirectory(path);
}catch (Exception e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}
/**
* 上传文件
* @param path保存FTP位置
* @param file要上传的文件
*/
public void upload(String path, File file) {
if(cdAssignPath(path)) {
try {
client.upload(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();
}
client.download(remoteName, new File(localPath + "/" + localName));
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 获取指定路径下的文件列表
* @param path
* @return
*/
public String[] ls(String path) {
try {
if(cdAssignPath(path)) {
return client.listNames();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 切换当前目录当根目录
*/
private void cdRoot() {
try {
while(!"/".equals(client.currentDirectory())) {
client.changeDirectoryUp();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 切换当前目录到指定路径,该路径必须从根路径开始
* @param path
* @return
*/
public boolean cdAssignPath(String path) {
boolean flag = true;
cdRoot();
try {
client.changeDirectory(path);
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
return flag;
}
}