1. 程式人生 > >java操作vaftpd實現上傳、下載

java操作vaftpd實現上傳、下載

1.配置檔案conf/vsftpd.properties

(我是單獨寫了一個配置檔案,你可以直接寫在application中)

vsftpd.ip=192.168.**.**
vsftpd.user=wangwei
vsftpd.pwd=123456
vsftpd.port=21
#ftp伺服器根路徑
vsftpd.remote.base.path=/var/ftp/wangwei
#ftp伺服器上的相對路徑【檔案路徑 =
/var/ftp/wangwei/images
vsftpd.remote.file.path
=/images
#檔案下載到本地的目錄位置
vsftpd.local.file.path
=F:/ftp/

2.操作類FtpUtil.java

package com.ch.evaluation.common.vsftpd.util;

import org.apache.commons.lang3.StringUtils;
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 org.apache.log4j.chainsaw.Main;
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.Properties; /** * @author wangwei * @date 2018/11/04 * ftp伺服器檔案上傳下載 */ public class FtpUtil { private static Logger LOGGER = LoggerFactory.getLogger(FtpUtil.class); private static String host; private
static String port; private static String username; private static String password; private static String basePath; private static String filePath; private static String localPath; /** *讀取配置檔案資訊 * @return */ public static void getPropertity(){ Properties properties = new Properties(); ClassLoader load = Main.class.getClassLoader(); InputStream is = load.getResourceAsStream("conf/vsftpd.properties"); try { properties.load(is); host=properties.getProperty("vsftpd.ip");//通用 port=properties.getProperty("vsftpd.port");//通用 username=properties.getProperty("vsftpd.user");//通用 password=properties.getProperty("vsftpd.pwd");//通用 basePath=properties.getProperty("vsftpd.remote.base.path");//伺服器 基路徑 filePath=properties.getProperty("vsftpd.remote.file.path");//伺服器 檔案路徑 localPath=properties.getProperty("vsftpd.local.file.path");//本地 下載到本地的目錄 } catch (IOException e) { e.printStackTrace(); } } /** * 上傳過載 * @param filename 上傳到伺服器埠重新命名 * @param sourceFilePathName 原始檔【路徑+檔案】 * @return */ public static boolean uploadFile(String filename, String sourceFilePathName) { getPropertity(); return uploadFile( host, port, username, password, basePath, filePath, filename, sourceFilePathName); } /** * 上傳過載 * @param filePath 上傳到伺服器的相對路徑 * @param filename 上傳到伺服器埠重新命名 * @param sourceFilePathName 原始檔【路徑+檔案】 * @return */ public static boolean uploadFile(String filePath,String filename, String sourceFilePathName) { getPropertity(); return uploadFile( host, port, username, password, basePath, filePath, filename, sourceFilePathName); } /** *下載過載 * @param fileName 要下載的檔名 * @return */ public static boolean downloadFile(String fileName) { getPropertity(); return downloadFile( host, port, username, password, basePath, filePath, fileName, localPath, null); } /** *下載過載 * @param filePath 要下載的檔案所在伺服器的相對路徑 * @param fileName 要下載的檔名 * @return */ public static boolean downloadFile(String filePath,String fileName) { getPropertity(); return downloadFile( host, port, username, password, basePath, filePath, fileName, localPath, null); } /** * 下載過載 * @param fileName 要下載的檔名 * @param filePath 要下載的檔案所在伺服器的相對路徑 * @param rename 下載後重命名[null或空不進行重新命名] * @return */ public static boolean downloadFile(String filePath,String fileName, String rename) { getPropertity(); return downloadFile( host, port, username, password, basePath, filePath, fileName, localPath, rename); } /** * 下載過載 * @param fileName 要下載的檔名 * @param localPath 下載時,到本地的路徑 * @param filePath 要下載的檔案所在伺服器的相對路徑 * @param rename 下載後重命名[null或空不進行重新命名] * @return */ public static boolean downloadFile(String filePath,String fileName,String localPath, String rename) { getPropertity(); return downloadFile( host, port, username, password, basePath, filePath, fileName, localPath, rename); } /** * Description: 向FTP伺服器上傳檔案 * @param host FTP伺服器hostname * @param port FTP伺服器埠 * @param username FTP登入賬號 * @param password FTP登入密碼 * @param basePath FTP伺服器基礎目錄 * @param filePath FTP伺服器檔案存放路徑。例如分日期存放:/2015/01/01。檔案的路徑為basePath+filePath * @param filename 上傳到FTP伺服器上的檔名 * @return 成功返回true,否則返回false */ public static boolean uploadFile(String host, String port, String username, String password, String basePath, String filePath, String filename, String sourceFilePathName) { boolean result = false; FTPClient ftp = new FTPClient(); try { int portNum = Integer.parseInt(port); int reply; ftp.connect(host, portNum);// 連線FTP伺服器 // 如果採用預設埠,可以使用ftp.connect(host)的方式直接連線FTP伺服器 ftp.login(username, password);// 登入 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return result; } //切換到上傳目錄 if (!ftp.changeWorkingDirectory(basePath+filePath)) { //如果目錄不存在建立目錄 String[] dirs = filePath.split("/"); String tempPath = basePath; for (String dir : dirs) { if (null == dir || "".equals(dir)) continue; tempPath += "/" + dir; if (!ftp.changeWorkingDirectory(tempPath)) { if (!ftp.makeDirectory(tempPath)) { return result; } else { ftp.changeWorkingDirectory(tempPath); } } } } //為了加大上傳檔案速度,將InputStream轉成BufferInputStream , InputStream input FileInputStream input = new FileInputStream(new File(sourceFilePathName)); BufferedInputStream in = new BufferedInputStream(input); //加大快取區 ftp.setBufferSize(1024*1024); //設定上傳檔案的型別為二進位制型別 ftp.setFileType(FTP.BINARY_FILE_TYPE); //上傳檔案 if (!ftp.storeFile(filename, in)) { return result; } in.close(); ftp.logout(); result = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return result; } /** * Description: 從FTP伺服器下載檔案 * @param host FTP伺服器hostname * @param port FTP伺服器埠 * @param username FTP登入賬號 * @param password FTP登入密碼 * @param basePath FTP伺服器上的相對路徑 * @param fileName 要下載的檔名 * @param localPath 下載後儲存到本地的路徑 * @return */ public static boolean downloadFile(String host, String port, String username, String password, String basePath, String filePath, String fileName, String localPath, String rename) { boolean result = false; FTPClient ftp = new FTPClient(); try { int portNum = Integer.parseInt(port); int reply; ftp.connect(host, portNum); // 如果採用預設埠,可以使用ftp.connect(host)的方式直接連線FTP伺服器 ftp.login(username, password);// 登入 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return result; } //ftp.changeWorkingDirectory(basePath);// 轉移到FTP伺服器目錄 if (!ftp.changeWorkingDirectory(basePath+filePath)) { LOGGER.info("伺服器端目錄不存在..."); } FTPFile[] fs = ftp.listFiles(); boolean flag = true; for (FTPFile ff : fs) { if (ff.getName().equals(fileName)) { flag = false; rename = StringUtils.isEmpty(rename)?ff.getName():rename; File localFile = new File(localPath + "/" + rename); OutputStream is = new FileOutputStream(localFile); ftp.retrieveFile(ff.getName(), is); is.close(); } } if(flag) LOGGER.info("伺服器端檔案不存在..."); ftp.logout(); result = true; } catch (IOException e) { LOGGER.info(e.getMessage()); e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return result; } }

3.測試

import com.ch.evaluation.common.vsftpd.util.FtpUtil;

public class ftpController {
    public static void main(String[] args) {

    /* boolean flag = FtpUtil.uploadFile("192.168.**.**", "21", "wangwei", "123456",
                    "/var/ftp/wangwei","/images", "handsome3.jpg", "F:\\ftp\\handSome.JPG");*/

    /* boolean flag = FtpUtil.uploadFile("/images1", "handsome.jpg", "F:\\ftp\\handSome.JPG");*/

     /* boolean flag = FtpUtil.uploadFile("handsome.jpg", "F:\\ftp\\handSome.JPG");*/

     /* boolean flag = FtpUtil.downloadFile("192.168.**.**", "21", "wangwei", "123456", "/var/ftp/wangwei/images",
                "handsome2.jpg", "F:/ftp/","");*/

boolean flag = FtpUtil.downloadFile("handsome2.jpg", "F:/ftp/"); System.out.println(flag); } }