commons-net网络开发包

2022-06-14 17:01:00 浏览数 (1)

commons-net以前用于ftp的文件上传和下载,现在差不多都忘记了,本文先做一个记录,方便后面如果要用也能随时找到

Apache Commons Net库是一个著名的Net库,包含了一组网络实用程序和协议实现。支持的协议包括Echo,Finger,FTP, NNTP,NTP,POP3(S),SMTP(S), Telnet, Whois等。使用Apache的commons-net实现FTP文件上传与下载工具类

org.apache.commons.net.ftp.FTPClient;,FTPClient封装了从FTP服务器存储和检索文件所需的所有功能。这个类处理了与FTP服务器交互的所有底层细节,并提供了一个方便的高级接口

官网地址

https://commons.apache.org/proper/commons-net/

引入的jar包

代码语言:javascript复制
		<dependency>
			<groupId>commons-net</groupId>
			<artifactId>commons-net</artifactId>
			<version>3.6</version>
		</dependency>

工具类(先保存,待验证)

代码语言:javascript复制
package com.bankedu.batch.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

import com.bankedu.core.util.lang.StringUtil;
import com.bankedu.web.common.Constants;
import com.bankedu.web.util.ParameterUtil;
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 com.bankedu.batch.model.Ftp;
import com.bankedu.web.util.Utils;


public class FtpUtil {
	private static Logger logger = Logger.getLogger(FtpUtil.class);

    private static FTPClient ftp;
    private static Ftp f;

    /**
     * 获取ftp连接
     * @param f
     * @return
     * @throws Exception
     */
    public static boolean connectFtp(Ftp f) {
		logger.info("【FTP工具类】=======进入connectFtp()======. ");
        ftp = new FTPClient();
        boolean flag = false;
        try {
			int reply;
			if (f.getPort() == null) {
			    ftp.connect(f.getIpAddr(), 21);
			} else {
			    ftp.connect(f.getIpAddr(), f.getPort());
			}
			ftp.setControlEncoding(f.getCharacter());
			ftp.login(f.getUserName(), f.getPwd());
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
			    ftp.disconnect();
			    return flag;
			}
			ftp.changeWorkingDirectory(f.getPath());
			logger.info("【FTP工具类】获取连接成功. ftp参数如下:"   ftp);
			flag = true;
		} catch (SocketException e) {
			logger.error("【FTP工具类】获取连接失败1: "   Utils.getExcetionMessage(e));
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("【FTP工具类】获取连接失败2: "   Utils.getExcetionMessage(e));
			e.printStackTrace();
		}
        return flag;
    }

    /**
     * 关闭ftp连接
     */
    public static void closeFtp() {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
    			logger.error("【FTP工具类】关闭连接失败: "   Utils.getExcetionMessage(e));
                e.printStackTrace();
            }
        }
    }

    /**
     * 从FTP服务器下载指定文件(只能下载文件, 不能下载文件夹)
     * @param remoteDir	远程路径
     * @param localDir	本地路径
     * @param fileName	需要下载的文件名
     * @return	true/false
     */
    public static boolean downloadFtpFile(String remoteDir, String localDir, String fileName) {
		logger.info("【FTP工具类】=======进入downloadFtpFile()======. ");
		logger.info("【FTP工具类】===remoteDir=" remoteDir ", localDir" localDir ", fileName" fileName);
//		ftp.enterLocalPassiveMode();//
        boolean isSussess = false;
    	try {
			ftp.changeWorkingDirectory(remoteDir);
			FTPFile[] ftpFiles = ftp.listFiles();

			for (FTPFile ftpFile : ftpFiles) {
				if (ftpFile.getName().equals(fileName)) {
					File localFile = new File(localDir   "/"   ftpFile.getName());
					OutputStream is = new FileOutputStream(localFile);
					isSussess = ftp.retrieveFile(ftpFile.getName(), is);
					is.close();
				}
			}
		} catch (FileNotFoundException e) {
			logger.error("【FTP工具类】下载文件失败: "   Utils.getExcetionMessage(e));
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("【FTP工具类】下载文件失败: "   Utils.getExcetionMessage(e));
			e.printStackTrace();
		}
    	return isSussess;
    }

    /**
     * 上传文件到FTP服务器(可上传文件/文件夹; 如果路径包含中文, 该文件会被忽略)
     * @param remotePath	需要上传到FTP服务器的路径
     * @param localFile		本地文件
     * @return	true/false
     */
    public static boolean uploadFtpFile(String remotePath, File localFile) {
        boolean isSussess = false;
        try {
        	logger.info("【FTP工具类】=======进入uploadFtpFile()======. remotePath=" remotePath "==localFile==" localFile);
        	logger.info("【FTP工具类】=======进入uploadFtpFile()======. localFile.isDirectory()=" localFile.isDirectory());
			if (localFile.isDirectory()) {
				remotePath = remotePath   "/"   localFile.getName();
				remotePath = new String(remotePath.getBytes("UTF-8"),"iso-8859-1");
				logger.info("【FTP工具类】=======进入uploadFtpFile()======remotePath222222=" remotePath);
			    boolean flag = ftp.changeWorkingDirectory(remotePath);
			    logger.info("【FTP工具类】=======进入uploadFtpFile()======remotePath222222= flag===" flag);
			    if(!flag){
			        ftp.makeDirectory(remotePath);
			        ftp.changeWorkingDirectory(remotePath);
			    }
			    String[] files = localFile.list();
			    logger.info("【FTP工具类】=======进入uploadFtpFile()======= files===" files);
			    for (String fstr : files) {
			        File file1 = new File(localFile.getPath()   "/"   fstr);
			        if (file1.isDirectory()) {
			        	uploadFtpFile(remotePath, file1);
			            ftp.changeToParentDirectory();
			        } else {
			            File file2 = new File(localFile.getPath()   "/"   fstr);
			            FileInputStream input = new FileInputStream(file2);
			            isSussess = ftp.storeFile(new String(file2.getName().getBytes("UTF-8"),"iso-8859-1"), input);
			            input.close();
			        }
			    }
			    logger.info("【FTP工具类】=======进入uploadFtpFile()======= 222222222222");
			} else {
				logger.info("【FTP工具类】=======进入uploadFtpFile()======= start 33333333333333333");
				remotePath = new String(remotePath.getBytes("UTF-8"),"iso-8859-1");
				//检查上传路径是否存在 如果不存在返回false
			    boolean flag = ftp.changeWorkingDirectory(remotePath);
			    logger.info("【FTP工具类】=======进入uploadFtpFile()======= end 33333333333333333  flag=" flag);
			    if(!flag){
			        //创建上传的路径  该方法只能创建一级目录,在这里如果/home/ftpuser存在则可创建image
			        ftp.makeDirectory(remotePath);
			        ftp.changeWorkingDirectory(remotePath);
			    }
			    FileInputStream input = new FileInputStream(localFile);
			    isSussess = ftp.storeFile(new String(localFile.getName().getBytes("UTF-8"),"iso-8859-1"), input);
			    input.close();
			    logger.info("【FTP工具类】=======进入uploadFtpFile()======= end 33333333333333333");
			}
		} catch (FileNotFoundException e) {
			logger.error("【FTP工具类】上传文件失败: "   Utils.getExcetionMessage(e));
			System.err.println("文件不存在");
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("【FTP工具类】上传文件失败: "   Utils.getExcetionMessage(e));
			System.err.println("IO异常");
			e.printStackTrace();
		}
        return isSussess;
    }

    /**
     * 删除FTP服务器上的文件(只能删除文件, 不能删除文件夹)
     * @param remotePath
     * @return true/false
     */
    public static boolean deleteFtpFile(String remotePath) {
        boolean isSussess = false;
    	try {
			if (!ftp.deleteFile(remotePath)) {
				System.err.println("文件不存在");
			}
			isSussess = true;
		} catch (IOException e) {
			logger.error("【FTP工具类】删除文件失败: "   Utils.getExcetionMessage(e));
			e.printStackTrace();
		}
        return isSussess;
    }

    /**
     * 校验文件是否存在(只能校验文件, 不能校验文件夹)
     * @param remotePath
     * @return
     */
    public static boolean isExits(String remotePath) {
        boolean isSussess = false;
        if(StringUtil.isFullEmptyOrNull(remotePath)){
        	logger.warn("isExits param error, remotePath=" remotePath);
        	return isSussess;
		}
    	try {
    		// ftp.changeWorkingDirectory(remotePath);
			// // 检验文件是否存在
			// InputStream is = ftp.retrieveFileStream(remotePath);
			// if (is == null || ftp.getReplyCode() == FTPReply.FILE_UNAVAILABLE) {
			//	return false;
			// }
			// if (is != null) {
			// 	is.close();
			// 	ftp.completePendingCommand();
			// }
			FTPFile[] ftpFiles = ftp.listFiles(remotePath);
			if(ftpFiles!=null || ftpFiles.length>0)
				isSussess = true;
			return isSussess;
		} catch (IOException e) {
			logger.error("【FTP工具类】判断文件是否存在失败: "   Utils.getExcetionMessage(e));
			e.printStackTrace();
		}
        return isSussess;
    }

//    @Before
	public void init() throws Exception {
    	f = new Ftp();
        f.setIpAddr("aliyun");
        f.setUserName("root");
        f.setPwd("ftproot");
        f.setCharacter("UTF-8");
        boolean connectFtp = FtpUtil.connectFtp(f);
        if (!connectFtp) {
			System.err.println("获取FTP连接失败");
		}
	}

//    @Test
	public void upload() throws Exception {
        String remotePath = "/哈哈";
        String localFileName = "/FTP/batchFiles/generate/QA/新建.txt";
        File localFile = new File(localFileName);
        System.out.println("上传文件开始。。。。");
        boolean isSussess = FtpUtil.uploadFtpFile(remotePath, localFile);//把文件上传在ftp上
        if (isSussess) {
        	System.out.println("上传文件成功。。。。");
		} else {
			System.out.println("上传文件失败。。。。");
		}
	}

//    @Test
    public void download() throws Exception {
    	String remoteDir = "/FTP/batchFiles/generate/QA/";
    	String localDir = "/FTP/batchFiles/generate/";
    	System.out.println("下载文件开始。。。。");
    	boolean isSussess = FtpUtil.downloadFtpFile(remoteDir, localDir, "QA_CERT_DEFINED_2018-12-19.TXT");
    	if (isSussess) {
    		System.out.println("下载文件成功。。。。");
    	} else {
    		System.out.println("下载文件失败。。。。");
    	}
    }

//    @Test
    public void delete() throws Exception {
    	String remotePath = "/tmpremoteFile/tmplocal";
    	boolean isSussess = FtpUtil.deleteFtpFile(remotePath);
    	if (isSussess) {
    		System.out.println("删除文件成功。。。。");
    	} else {
    		System.out.println("删除文件失败。。。。");
    	}
    }

//    @Test
    public void isExists() throws Exception {
    	String remotePath = "/tmpremoteFile/tmplocal";
    	boolean isSussess = FtpUtil.isExits(remotePath);
    	if (isSussess) {
    		System.out.println(remotePath   "文件存在。。。。");
    	} else {
    		System.out.println(remotePath   "文件不存在。。。。");
    	}
    }

}

0 人点赞