ftp工具类

ftp依赖 

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

 代码:


/**
 * 列出FTP服务器上指定目录下面的所有文件
 *
 */
public class FtpUtils {

    private FTPClient ftp;
    private ArrayList<String> arFiles;

    /**
     * 重载构造函数
     *
     * @param isPrintCommmand 是否打印与FTPServer的交互命令
     */
    public FtpUtils(boolean isPrintCommmand) {
        ftp = new FTPClient();
        arFiles = new ArrayList<String>();
        if (isPrintCommmand) {
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        }
    }

    /**
     * 登陆FTP服务器
     *
     * @param host     FTPServer IP地址
     * @param port     FTPServer 端口
     * @param username FTPServer 登陆用户名
     * @param password FTPServer 登陆密码
     * @return 是否登录成功
     * @throws IOException
     */
    public boolean login(String host, int port, String username, String password) throws IOException {
        this.ftp.connect(host, port);
        if (FTPReply.isPositiveCompletion(this.ftp.getReplyCode())) {
            if (this.ftp.login(username, password)) {
                this.ftp.setControlEncoding("UTF-8");
                this.ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                this.ftp.enterLocalPassiveMode();
                return true;
            }
        }
        if (this.ftp.isConnected()) {
            this.ftp.disconnect();
        }
        return false;
    }

    /**
     * 关闭数据链接
     *
     * @throws IOException
     */
    public void disConnection() throws IOException {
        if (this.ftp.isConnected()) {
            this.ftp.disconnect();
        }
    }


    /**
     * 根据文件的开头和结尾遍历ftp文件夹
     *
     * @param pathName  需要遍历的目录,必须以File.separator开始和结束
     * @param startwith 文件名开头
     * @param endwith   文件名结尾
     * @return
     * @throws IOException
     */
    public List<String> list(String pathName, String startwith, String endwith) throws IOException {
        if (pathName.startsWith(File.separator) && pathName.endsWith(File.separator)) {
            String directory = pathName;
            // 更换目录到当前目录
            if (!this.ftp.changeWorkingDirectory(directory)) {
                return null;
            }
            FTPFile[] files = this.ftp.listFiles();
            for (FTPFile file : files) {
                if (file.isFile()) {
                    if (file.getName().endsWith(endwith) && file.getName().startsWith(startwith)) {
                        arFiles.add(file.getName());
                    }
                } else if (file.isDirectory()) {
                    list(directory + file.getName() + File.separator, startwith, endwith);
                }
            }
        }
        return arFiles;
    }

    /**
     * 根据指定的路径和文件名下载
     *
     * @param locaPath 路径
     * @param fileName 文件名
     * @return
     */
    public boolean download(String locaPath, String fileName) {
        File path = new File(locaPath);
        if (!path.exists()) {
            path.mkdirs();
        }
        boolean b = false;
        File localFile = new File(locaPath + File.separatorChar + fileName);
        OutputStream os;
        try {
            if (localFile != null) {
                os = new FileOutputStream(locaPath + File.separatorChar + fileName);
                b = this.ftp.retrieveFile(fileName, os);
                os.close();
//			if(Global.getConfig("news.ftp.delete").equals("delete"))
                this.ftp.deleteFile(fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }

    public static void main(String[] args) throws Exception {
		/**String thisDayFmt = File.separator + "yyyy" + File.separator + "MM" + File.separator + "dd" + File.separator;
		String thisDayPath = DateUtils.formatDate(new Date(), thisDayFmt);
		List<String> list = null;
		FtpUtils f = new FtpUtils(false);
		if (f.login("1.203.114.38", 9040, "xzptxw", "zfwbwj904051")) {
			list = f.list(thisDayPath, "zip");
		}
		if (list != null && list.size() > 0) {
			boolean d = f.download("D:\\ftp" + thisDayPath, list.get(0));
			System.out.println("download=" + d);
		}
		f.disConnection();
		
       */
    }


}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个Java的FTP工具类的示例代码: ```java import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import java.io.*; public class FTPUtil { private FTPClient ftpClient; public FTPUtil() { ftpClient = new FTPClient(); } public boolean connect(String server, int port, String user, String password) { try { ftpClient.connect(server, port); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { return false; } boolean success = ftpClient.login(user, password); if (!success) { return false; } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } public boolean uploadFile(String localFilePath, String remoteFilePath) { try (InputStream inputStream = new FileInputStream(localFilePath)) { return ftpClient.storeFile(remoteFilePath, inputStream); } catch (IOException e) { e.printStackTrace(); return false; } } public boolean downloadFile(String remoteFilePath, String localFilePath) { try (OutputStream outputStream = new FileOutputStream(localFilePath)) { return ftpClient.retrieveFile(remoteFilePath, outputStream); } catch (IOException e) { e.printStackTrace(); return false; } } public boolean disconnect() { try { ftpClient.logout(); ftpClient.disconnect(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } } ``` 使用该工具类,你可以连接到FTP服务器,上传文件和下载文件。你需要引入Apache Commons Net库,该库提供了FTP客户端的实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值