1. 程式人生 > >Java實現FTP伺服器檔案的上傳和下載

Java實現FTP伺服器檔案的上傳和下載

一、前言:

最近剛好需要實現這個功能:實現ftp的上傳和下載。在網上找了下資料,總結了下。直接上程式碼:

二、程式碼示例:

首先使用到的maven依賴:

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>1.4.1</version>
</dependency>

ftp工具類:

package com.left.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;

/**
 * <pre>
 *     @author : orange
 *     e-mail : 
[email protected]
* time : 2018/10/09 14:18 * desc : ftp下載工具 * version: 1.0 * </pre> */ @Slf4j public class FtpUtil { /** * 獲取FTPClient物件 * * @param ftpHost FTP主機伺服器 * @param ftpPassword FTP 登入密碼 * @param ftpUserName FTP登入使用者名稱 * @param ftpPort FTP埠 預設為21 * @return */ public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) { FTPClient ftpClient = new FTPClient(); try { ftpClient = new FTPClient(); ftpClient.connect(ftpHost, ftpPort);// 連線FTP伺服器 ftpClient.login(ftpUserName, ftpPassword);// 登陸FTP伺服器 if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { System.out.println("未連線到FTP,使用者名稱或密碼錯誤。"); ftpClient.disconnect(); } else { System.out.println("FTP連線成功。"); } } catch (SocketException e) { e.printStackTrace(); System.out.println("FTP的IP地址可能錯誤,請正確配置。"); } catch (Exception e) { e.printStackTrace(); System.out.println("FTP的埠錯誤,請正確配置。"); } return ftpClient; } /* * 從FTP伺服器下載檔案 * * @param ftpHost FTP IP地址 * @param ftpUserName FTP 使用者名稱 * @param ftpPassword FTP使用者名稱密碼 * @param ftpPort FTP埠 * @param ftpPath FTP伺服器中檔案所在路徑 格式: ftptest/aa * @param localPath 下載到本地的位置 格式:H:/download * @param fileName 檔名稱 */ public static boolean downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String localPath, String fileName) { FTPClient ftpClient = null; try { ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); ftpClient.setControlEncoding("UTF-8"); // 中文支援 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(ftpPath); File localFile = new File(localPath + File.separatorChar + fileName); OutputStream os = new FileOutputStream(localFile); ftpClient.retrieveFile(fileName, os); os.close(); ftpClient.logout(); } catch (FileNotFoundException e) { log.info("沒有找到" + ftpPath + "檔案"); e.printStackTrace(); return false; } catch (SocketException e) { log.info("連線FTP失敗."); e.printStackTrace(); return false; } catch (Exception e) { log.info("檔案讀取錯誤。"); e.printStackTrace(); return false; } return true; } /** * Description: 向FTP伺服器上傳檔案 * * @param ftpHost FTP伺服器hostname * @param ftpUserName 賬號 * @param ftpPassword 密碼 * @param ftpPort 埠 * @param ftpPath FTP伺服器中檔案所在路徑 格式: ftptest/aa * @param fileName ftp檔名稱 * @param input 檔案流 * @return 成功返回true,否則返回false */ public static boolean uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String fileName, InputStream input) { boolean success = false; FTPClient ftpClient = null; try { int reply; ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); return success; } ftpClient.setControlEncoding("UTF-8"); // 中文支援 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(ftpPath); ftpClient.storeFile(fileName, input); input.close(); ftpClient.logout(); success = true; } catch (Exception e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ioe) { } } } return success; } /** * 方法描述:檢驗指定路徑的檔案是否存在ftp伺服器中 * * @param filePath 指定絕對路徑的檔案/TEST/20161010 * @return 存在返回true,不存在返回false */ public static boolean isFTPFileExist(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String fileName, String filePath) { FTPClient ftpClient = null; try { ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); ftpClient.setControlEncoding("GBK"); // 中文支援 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); // 進入檔案所在目錄,注意編碼格式,以能夠正確識別中文目錄 ftpClient.changeWorkingDirectory(new String(filePath.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING)); // 檢驗檔案是否存在 InputStream is = ftpClient.retrieveFileStream(new String(fileName .getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING)); if (is == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE) { log.info("檔案" + filePath + "/" + fileName + "不存在"); return false; } log.info("檔案" + filePath + "/" + fileName + "存在"); if (is != null) { is.close(); ftpClient.completePendingCommand(); } } catch (Exception e) { e.printStackTrace(); return false; } finally { if (ftpClient != null) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); return false; } } } return true; } public static void main(String[] args) { String ftpHost = "60.12.107.83"; String ftpUserName = "sl0571"; String ftpPassword = "sl123456"; int ftpPort = 10021; String ftpPath = "/data/yzf_ftp/kwy_ftp"; String localPath = "E:\\card"; String fileName = "20181014.txt"; // FTPClient ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); boolean ftpFileExist = isFTPFileExist(ftpHost, ftpUserName, ftpPassword, ftpPort, fileName, ftpPath); if(ftpFileExist) { boolean downloadFtpFile = downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName); System.out.println("下載結果:" + downloadFtpFile); } // } } }