您的位置:首页 > 编程语言 > PHP开发

FTPClient 处理多个文件时注意添加completePendingCommand

2016-03-31 11:02 585 查看
<span style="font-family:Arial, Helvetica, sans-serif;">//楼主之前做一个项目对接,要求用到操作ftp文件等功能,主要遇到的问题是当要遍历文件夹里的文件时或者下载所有文件时,如果没有使用completePendingCommand()这方//法,则只能处理一个文件,在处理第二个文件的时候(即第二次调用retrieveFileStream()方法的时候)返回null。</span>
<span style="font-family:Arial, Helvetica, sans-serif;">//所以处理第二个文件前,必须使用completePendingCommand()方法</span>
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

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

/**
* 先链接,再进行操作

*/
public class FTPUtil {

private FTPClient ftp;

//链接ftp
public boolean connect(String path,String addr,int port,String username,String password){
ftp = new FTPClient();
try {
//			ftp.connect(addr, port);
ftp.connect(addr);
ftp.login(username, password);
if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())){
ftp.disconnect();
return false;
}
ftp.changeWorkingDirectory(path);
return true;
} catch (SocketException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

//上传文件
public boolean upLoadFile(File file){
try {
FileInputStream input = new FileInputStream(file);
ftp.storeFile(file.getName(), input);
input.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

//断开连接
public boolean disconnect(){
try {
return ftp.logout();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

//获取对应文件夹里的所有文件
public FTPFile[] listFile(){
try {
return ftp.listFiles();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

//返回输入流
public InputStream returnFileStream(String fileName){
try {
return ftp.retrieveFileStream(fileName);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

//设置处理多个文件
public boolean completePendingCommand(){
try {
return ftp.completePendingCommand();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

//删除文件
public boolean deleteFile(String fileName){
try {
return ftp.deleteFile(fileName);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: