|
最近的工作中,需要定时操作FTP服务器上的文件,用到了FTPClient
记录并分享一下使用心得
首先当然是引包 commons-net-2.0.jar
这样你就可以使用FTPClient这个类创建用于连接FTP服务器的对象了
具体方法见代码:
FTPClient ftpClient = new FTPClient();
private String serverIP;
private Integerport;
private String username;
private String password;
以下是连接到FTP服务器的代码,返回true 就代表ftpClient已经成功连接到FTP服务器了,也就是可以操作FTP服务器上的文件了
public boolean getReady(){
boolean succeed = false;
try {
int replyCode;
ftpClient.connect(this.serverIP, this.port);
replyCode = ftpClient.getReplyCode();
if(FTPReply.isPositiveCompletion(replyCode)) {
succeed = ftpClient.login(this.username, this.password);
}
if(!succeed){
log.error("ftp login error:"+ftpClient.getReplyString());
}else{
log.debug("FTP Server "+ this.serverIP +" is Connected......");
}
} catch (Exception exp) {
log.error("connect ftp server error:"+this.serverIP+" "+exp.getMessage());
if(ftpClient.isConnected()){
this.disConnect();
}
}
return succeed;
}
下面再来两个操作文件的方法做演示
获取文件列表(当然返回的是文件名集合)
public List<String> list(String filePath) {
FTPFile[] files;
List<String> result = new ArrayList<String>();
if (this.getReady()) {
try {
files = ftpClient.listFiles(filePath);
for (FTPFile file : files) {
if (file.isFile()) {
result.add(file.getName());
}
}
} catch (IOException e) {
log.error("gen file list error:" + filePath + "\r\n"
+ e.getMessage());
}
}
return result;
}
删除FTP指定文件(小心操作哦)
/**
* 删除指定文件
* @param pathname
* @return
* @throws IOException
*/
public void deleteFile(String pathname) {
try {
if(this.getReady()){
this.ftpClient.deleteFile(pathname);
log.info("成功删除数据========"+pathname);
}
} catch (Exception e) {
log.error("非法参数路径[" + pathname + "]", e);
}
}
以上只做简单介绍,希望对初次使用的有引导作用
|
|
|
|
|
|
|