162
技術社區[雲棲]
java 實現ftp文件的獲取跟下載
SpringBoot 中實現從ftp文件服務器中獲取文件。
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;
import org.springframework.stereotype.Component;
import java.io.*;
/**
* Created by IntelliJ IDEA.
* Project: sits-hbc-collect
* User : chenlong
* Date : 17/07/11
* Time : 14:38
*/
@Component
public class FtpClient {
protected static Logger logger = Logger.getLogger(FtpClient.class);
/**
* 本地字符編碼
*/
private static String LOCAL_CHARSET = "GBK";
// FTP協議裏麵,規定文件名編碼為iso-8859-1
private static String SERVER_CHARSET = "ISO-8859-1";
/**
* Description: 從FTP服務器下載文件
*
* @param url FTP服務器hostname
* @param port FTP服務器端口
* @param username FTP登錄賬號
* @param password FTP登錄密碼
* @param remotePath FTP服務器上的相對路徑
* @param fileName 要下載的文件名
* @param localPath 下載後保存到本地的路徑
* @return
* @Version. Jul , :: PM by 陳龍 創建
*/
public boolean downFile(String url, int port, String username, String password, String remotePath, String fileName, String localPath) {
String myCharset = System.getProperty("file.encoding");//查看係統編碼
logger.info("================file.encoding:"+myCharset);
boolean success = false;
FTPClient ftp = new FTPClient();
try {
//如果采用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
boolean login = login(ftp, url, port, username, password);//登錄
if (login) {
if (remotePath.startsWith("/") && remotePath.endsWith("/")) {
String p = new String(remotePath.getBytes("gbk"), ftp.DEFAULT_CONTROL_ENCODING);
logger.info("================remotePath:"+p);
System.out.println(p);
boolean path = ftp.changeWorkingDirectory(new String(remotePath.getBytes(LOCAL_CHARSET), ftp.DEFAULT_CONTROL_ENCODING));//轉移到FTP服務器目錄
if (!path) {
logger.error("ftp 服務器進入路徑:" + remotePath + " 失敗!");
} else {
logger.info("ftp 服務器進入路徑:" + remotePath + " 成功!");
System.out.println("進入黃標車路徑成功");
list(ftp, fileName, localPath);
}
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
logger.error("ftp 服務器:" + e.getMessage());
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
logger.error(ioe.getMessage());
}
}
}
logger.info("outside文件獲取成功!");
try {
disConnection(ftp);
} catch (IOException e) {
e.printStackTrace();
}
return success;
}
/**
* 登陸FTP服務器
*
* @param ftp
* @param host FTPServer IP地址
* @param port FTPServer 端口
* @param username FTPServer 登陸用戶名
* @param password FTPServer 登陸密碼
* @return 是否登錄成功
* @throws IOException
*/
public static boolean login(FTPClient ftp, String host, int port, String username, String password) throws IOException {
ftp.connect(host, port);
if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
if (ftp.login(username, password)) {
if (FTPReply.isPositiveCompletion(ftp.sendCommand("OPTS UTF8", "ON"))) {// 開啟服務器對UTF-8的支持,如果服務器支持就用UTF-8編碼,否則就使用本地編碼(GBK).
LOCAL_CHARSET = "UTF-8";
}
ftp.setControlEncoding(LOCAL_CHARSET);
ftp.enterLocalActiveMode();// 設置主動模式
return true;
}
}
if (ftp.isConnected()) {
ftp.disconnect();
}
return false;
}
/**
* 關閉數據鏈接
*
* @param ftp
* @throws IOException
*/
public void disConnection(FTPClient ftp) throws IOException {
if (ftp.isConnected()) {
ftp.disconnect();
}
}
private void list(FTPClient ftp, String fileName, String localPath) {
try {
ftp.printWorkingDirectory();
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
// 提取絕對地址的目錄以及文件名
logger.info("ftp get fire name ========================:" + ff.getName());
// 進入文件所在目錄,注意編碼格式,以能夠正確識別中文目錄
//排除前兩層目錄
if (ff.getName().equals(".") || ff.getName().equals("..")) {
continue;
} else if (ff.isFile()) {
String fileN = ff.getName().substring(0, 8);
if (fileN.equals(fileName)) {
File localFile = new File(localPath + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.flush();
is.close();
}
} else if (ff.isDirectory()) {
String file = ff.getName();
logger.info("ftp ff.getName().length():" + file.length());
String fileN = ff.getName().substring(file.length() - 8, file.length());
System.out.println(fileN);
if (fileN.equals(fileName)) {
boolean path = ftp.changeWorkingDirectory(new String(file.getBytes(LOCAL_CHARSET), ftp.DEFAULT_CONTROL_ENCODING));//轉移到FTP服務器目錄
if (path){
list(ftp, fileName, localPath);
}else{
logger.error("ftp 服務器進入路徑:" + ff.getName() + " 失敗!");
}
}
}
}
} catch (Exception e) {
logger.error("ftp 服務器錯誤:" + e.getMessage());
}
}
}
最後更新:2017-07-25 14:32:35