1、引入maven配置(commons-net,當前版本最新3.6);
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
2、下面是源碼:
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
/**
* Ftp訪問 <br/>
* Created by claireliu on 2017/5/23.
*/
public class FtpFunction {
private static Logger log = Logger.getLogger(FtpFunction.class);
static FTPClient ftp;
public static boolean getConnect() {
boolean result = false;
try {
int port = 21;
String address = "127.0.0.1";
String userName = "bbb";
String userPassword = "ccc";
ftp = new FTPClient();
ftp.connect(address, port);
ftp.login(userName, userPassword);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.setControlEncoding("GBK");
// 調用FTPClient.enterLocalPassiveMode();這個方法的意思就是每次數據連接之前,ftp
// client告訴ftp server開通一個端口來傳輸數據。爲什麼要這樣做呢,因爲ftp
// server可能每次開啓不同的端口來傳輸數據,但是在linux上,由於安全限制,可能某些端口沒有開啓,所以就出現阻塞(會出現下載不了的情況或者listfiles爲空。)。
ftp.enterLocalPassiveMode();
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
result = true;
} catch (Exception e) {
e.printStackTrace();
log.error("op<getConnect> getConnect fail", e);
}
return result;
}
/**
* 下載
* @param remotePath ftp服務器上的路徑
* @param fileName 文件名
* @param localPath 本地的存儲路徑。
* @return 成功與否
*/
public static boolean downFileSimpleFile(String remotePath, String fileName, String localPath) {
boolean success = false;
OutputStream is = null;
try {
getConnect();
String remoteFileName = remotePath + File.separator + fileName;
File localFile = new File(localPath + File.separator + fileName);
is = new FileOutputStream(localFile);
ftp.setBufferSize(1024);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
ftp.retrieveFile(remoteFileName, is);
success = true;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally {
close(is);
}
return success;
}
private static void close(OutputStream is) {
try {
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
}
3、調用:
FtpFunction.downFileSimpleFile("logFile", "file_20170515112505.txt", "/opt/");