<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;
}
}
}