/**
遇到的問題:
1.防火牆阻止
2.代理軟件限制,服務器需要通過代理訪問外網,但FTP是內網直接可以訪問的.(花費我一下午找該問題- -)
3.解決中文目錄問題
支持JAR :commons-net-3.5.jar
**/
package rservice;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FTP {
private static final Logger log = LoggerFactory.getLogger(FTP.class);
public static boolean downFile(
String url, //FTP服務器hostname
int port,//FTP服務器端口
String username, //FTP登錄賬號
String password, //FTP登錄密碼
String fileName,//要下載的文件名
String localPath,//下載後保存到本地的路徑
String remotePath//FTP服務器上的相對路徑
) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);
//如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
boolean login=ftp.login(username, password);//登錄
ftp.setControlEncoding("GBK");
//設置環境
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
ftp.configure(conf);
reply = ftp.getReplyCode();
log.error("remotePath:"+remotePath);
System.out.println("login:"+login+" reply:"+reply);
log.error("login:"+login+" reply:"+reply);
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
boolean chg=ftp.changeWorkingDirectory(new String(remotePath.getBytes("GBK"),"ISO-8859-1"));//轉移到FTP服務器目錄
log.error("remote path:" + ftp.printWorkingDirectory());
System.out.println("changeWorkingDirectory:"+chg);
if(chg){
FTPFile[] fs = ftp.listFiles();
System.out.println("files...."+fs.length);
log.error("files...."+fs.length);
for(FTPFile ff:fs){
if(ff.getName().equals(fileName)){
File localFile = new File(localPath+"/"+ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
success = true;
}else{
success = false;
}
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
}
JAVA 從FTP目錄中下載文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.