java 中 FtpClient 實現 FTP 檔案上傳、下載
阿新 • • 發佈:2018-12-30
package ftp;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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;
import org.apache.log4j.Logger;
/**
* ftp 上傳、下載工具類
* @author JiangYu
*/
public class FtpUtil {
private static Logger logger = Logger.getLogger(FtpUtil.class);
/**
* 獲取FTPClient物件
* @param ftpHost FTP主機伺服器
* @param ftpPassword FTP 登入密碼
* @param ftpUserName FTP登入使用者名稱
* @param ftpPort FTP埠 預設為21
* @return
*/
public static FTPClient getFTPClient(String ftpHost, String ftpPassword,
String ftpUserName, int ftpPort) {
FTPClient ftpClient = null;
try {
ftpClient = new FTPClient();
ftpClient.connect(ftpHost, ftpPort);// 連線FTP伺服器
ftpClient.login(ftpUserName, ftpPassword);// 登陸FTP伺服器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
logger.info("未連線到FTP,使用者名稱或密碼錯誤 !");
ftpClient.disconnect();
} else {
logger.info("FTP連線成功。");
}
} catch (SocketException e) {
e.printStackTrace();
logger.info("請檢查FTP的IP地址 ! ");
} catch (IOException e) {
e.printStackTrace();
logger.info("請核對FTP的埠 ! ");
}
return ftpClient;
}
/**
* 上傳本地檔案到FTP伺服器
* @param ftpPath 伺服器上存放檔案的路徑
* @param ftpUserName ftp服務賬號
* @param ftpPassword ftp服務密碼
* @param ftpHost ftp服務ip
* @param ftpPort ftp服務埠
* @param fileContent 檔案內容
* @param writeTempFielPath 檔案在本地的路徑
*/
public static String upload(String ftpPath, String ftpUserName, String ftpPassword,
String ftpHost, int ftpPort, String fileContent, String writeTempFielPath) {
FTPClient ftpClient = null;
String uploadResult = "";
try {
ftpClient = getFTPClient(ftpHost, ftpPassword,
ftpUserName, ftpPort);
// 設定PassiveMode傳輸
ftpClient.enterLocalPassiveMode();
// 設定以二進位制流的方式傳輸
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 對遠端目錄的處理
String remoteFileName = ftpPath;
if (ftpPath.contains("/")) {
remoteFileName = ftpPath
.substring(ftpPath.lastIndexOf("/") + 1);
}
// 先把檔案寫出到本地,再上傳到FTP上,最後再刪除 。
String result = write(remoteFileName, fileContent,
writeTempFielPath);
if (result.contains("成功")) {
File f = new File(writeTempFielPath + "/" + remoteFileName);
InputStream in = new FileInputStream(f);
ftpClient.storeFile(remoteFileName, in);
in.close();
uploadResult = "檔案" + remoteFileName + "上傳成功!";
f.delete(); // 刪除本地臨時檔案
} else {
uploadResult = "檔案" + remoteFileName + "上傳失敗!";
}
return uploadResult;
} catch (Exception e) {
e.printStackTrace();
return uploadResult+"錯誤源: "+e.getMessage();
}finally{
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 檔案寫出到本地
* @param fileName 檔名
* @param fileContext 檔案內容
* @param writeTempFielPath 本地儲存路徑
* @return
*/
public static String write(String fileName, String fileContext,
String writeTempFielPath) {
String result = "寫出成功 !";
try {
File f = new File(writeTempFielPath + "/" + fileName);
if(!f.exists()){
if(!f.createNewFile()){
result = "檔案不存在,建立失敗 !";
}
}
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.write(fileContext.replaceAll("\n", "\r\n"));
bw.flush();
bw.close();
return result;
} catch (Exception e) {
result = "寫出失敗 !";
e.printStackTrace();
return result;
}
}
/**
* 從FTP伺服器下載檔案
* @param ftpHost FTP伺服器IP
* @param port FTP伺服器埠
* @param username FTP登入賬號
* @param password FTP登入密碼
* @param remotePath FTP伺服器上的相對路徑
* @param fileName 要下載的檔名
* @param localPath 下載後儲存到本地的路徑
* @return
*/
public static String downFile(String ftpHost, int port,String username, String password,
String remotePath,String fileName,String localPath) {
String result = "下載失敗 !";
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(ftpHost, port);
ftp.login(username, password); // 登入
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return "服務連線失敗 !";
}
ftp.changeWorkingDirectory(remotePath); // 轉移到FTP伺服器目錄
FTPFile[] fs = ftp.listFiles();
boolean flag = false; // 下載檔案不存在
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();
flag = true;
}
}
ftp.logout();
if(!flag){
result = "檔案: "+fileName+"不存在 !";
}else{
result = "下載成功 !";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {}
}
}
return result;
}
}