通过java连接ftp下载指定目录下的所有文件,过滤掉临时文件。

通过java连接ftp下载指定目录下的所有文件,过滤掉临时文件。

采用递归的方式。

package com.qxj.word.timer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/*******************************************************************************

  • 功能说明: 从ftp服务器指定目录复制文件到本地指定路径

  • @author qianshu

  • @time 2012-6-25
    ******************************************************************************/
    public class FtpDownFiles {

    private FTPClient ftpClient;

    public FtpDownFiles() {
    this.ftpClient = new FTPClient();
    }

    /**

    • 功能说明:通过递归实现ftp目录文件与本地文件同步更新
    • @param ftpfilepath
    •        当前ftp目录
      
    • @param localpath
    •        当前本地目录
      

    */
    public void ftpDownFiles(String ftpfilepath, String localpath) {

     try {
     	String load1 = ftpfilepath;
     	FTPFile[] ff = getFileDir(load1);
     	//System.out.println(ftpfilepath);
     //	FTPFile[] ff = ftpClient.listFiles(ftpfilepath);
     	// 得到当前ftp目录下的文件列表
    
     	if (ff != null) {
     		for (int i = 0; i < ff.length; i++) {
     			if(ff[i].getName().indexOf(".doc")!=-1&&ff[i].getName().indexOf("~$")==-1){
     				//System.out.println(ff[i].getName());
     				String localfilepath = localpath + ff[i].getName();
     				File localFile = new File(localfilepath);
     				// 根据ftp文件生成相应本地文件
     				Date fflastModifiedDate = ff[i].getTimestamp().getTime();
     				// 获取ftp文件最后修改时间
     				Date localLastModifiedDate = new Date(localFile
     						.lastModified());
     				// 获取本地文件的最后修改时间
     				int result = localLastModifiedDate
     						.compareTo(fflastModifiedDate);
     				// result=0,两文件最后修改时间相同;result<0,本地文件的最后修改时间早于ftp文件最后修改时间;result>0,则相反
     				if (ff[i].isDirectory()) {
     					// 如果是目录
     					localFile.mkdir();
     					// 如果本地文件夹不存在就创建
     					String ftpfp = ftpfilepath + ff[i].getName() + "/";
     					// 转到ftp文件夹目录下
     					String localfp = localfilepath + "/";
     					// 转到本地文件夹目录下
     					this.ftpDownFiles(ftpfp, localfp);
     					// 递归调用
    
     				}
     				if (ff[i].isFile()) {
     					// 如果是文件
     					File lFile = new File(localpath);
     					lFile.mkdir();
     					// 如果文件所在的文件夹不存在就创建
     					if (!lFile.exists()) {
     						return;
     					}
     					if (ff[i].getSize() != localFile.length() || result < 0) {
     						// 如果ftp文件和本地文件大小不一样或者本地文件不存在或者ftp文件有更新,就进行创建、覆盖
     						String filepath = ftpfilepath + ff[i].getName();
     						// 目标ftp文件下载路径
     						FileOutputStream fos = new FileOutputStream(
     								localFile);
     						boolean boo;
     						try {
     							boo = ftpClient.retrieveFile(new String(
     									filepath.getBytes("GBK"),
     									"ISO-8859-1"), fos);
     							// 从FTP服务器上取回一个文件
     						} catch (Exception e) {
     							boo = false;
     							e.printStackTrace();
     						}
    
     						if (boo == true) {
     							String name=ff[i].getName();
     							String dir=localpath;
     							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     							String time=sdf.format(localFile.lastModified());
    

// Start test=new Start();
// test.getConn(name, dir, time);
System.out.println(name+" “+dir+” "+time);
} else {

							}

							fos.flush();
							// 将缓冲区中的数据全部写出
							fos.close();
							// 关闭流
						} else {
							//	System.out.println("两个文件相同!");
						}
					}

				}
				}

		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();

	}

}


/**
 * 功能说明:连接ftp服务器
 * 
 * @param hostip
 *            服务器地址
 * @param username
 *            用户名
 * @param password
 *            密码
 */
public void connectServer(String hostip,Integer port,String username, String password) {

	try {
		ftpClient.connect(hostip, port);
		// 连接服务器
		ftpClient.login(username, password);
		// 登录
		// 检测是否连接成功
		int reply = ftpClient.getReplyCode();
		// 看返回的值是不是230,如果是,表示登陆成功
		if (!FTPReply.isPositiveCompletion(reply)) {
			// 返回的code>=200&&code<300return
			ftpClient.disconnect();
			// 关闭FTP连接
		}
		ftpClient.setControlEncoding("GBK");
		// 设置字符编码
		ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
		// 设置文件传输格式

	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();

	}

}

public String Loadingpaths(String parameterKey) {
	{
		String load = null;
		Properties properties = new Properties();
		try {
			properties.load(this.getClass().getResourceAsStream("/loadpath.properties"));
			load = properties.getProperty(parameterKey);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return load;
	}
}

public FTPFile[] getFileDir(String path1) throws IOException {
	//   FTPListAllFiles ss=new FTPListAllFiles(true);

  /*  FTPFile[] files=null;
    FTPListAllFiles f = new FTPListAllFiles(true);
    if (f.login("172.24.179.34", 21, "decis", "decis")) {
        String pathName=path1;
        String ss=new String(pathName.getBytes("GBK"),"iso-8859-1");
        //  this.ftp.changeWorkingDirectory(ss);

        boolean dir=this.ftp.changeWorkingDirectory(ss);
        System.out.println(dir);
        files = this.ftp.listFiles();
        System.out.println("1111");
        return files;
    }
    return files;*/
	FTPListAllFiles ss=new FTPListAllFiles(true);
	FTPFile[] files=ss.diaoyong(path1);
	return  files;
}

/**
 * 功能说明:根据ftp文件30秒刷新一次本地文件
 * 
 * @param args
 */
public static void main1(String[] args) {

	while (true) {
		try {

			FtpDownFiles fd = new FtpDownFiles();
			fd.connectServer("172.24.179.34",21 ,"decis", "decis");
			fd.ftpDownFiles("/决策服务产品/2019年决策服务产品/每日气象要讯/", "D:\\本地移动服务器下载文件\\决策服务产品\\2019年决策服务产品\\每日气象要讯\\");
			fd.ftpDownFiles("/2019年决策服务产品/主城六区每日气象要讯/", "D:\\本地移动服务器下载文件\\2019年决策服务产品\\主城五区每日气象要讯\\");
			fd.ftpDownFiles("/气候产品/延伸期预报/", "D:\\本地移动服务器下载文件\\气候产品\\延伸期预报\\");
			fd.ftpDownFiles("/气候产品/短期气候预测/", "D:\\本地移动服务器下载文件\\气候产品\\短期气候预测\\");
			fd.ftpDownFiles("/气候产品/气候影响评价/", "D:\\本地移动服务器下载文件\\气候产品\\气候影响评价\\");




			System.out.println("-----");
		} catch (Exception e) {
			System.out.println("读取异常");
		}

		try {
			Thread.sleep(30 * 1000);
		} catch (Exception e) {
		}
	}

}

}
如果有运行错误opening ascii mode data connection
请关闭防火墙

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用Java实现FTP下载远程服务器指定目录下所有文件的示例代码: ```java import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; 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; public class FTPDownloadDemo { public static void main(String[] args) { String server = "your.ftp.server.com"; int port = 21; String user = "username"; String password = "password"; String remoteDirPath = "/remote/directory/path"; String localDirPath = "/local/directory/path"; FTPClient ftpClient = new FTPClient(); try { // 连接FTP服务器 ftpClient.connect(server, port); // 登录FTP服务器 ftpClient.login(user, password); // 检查连接和登录是否成功 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); return; } System.out.println("Connected to FTP server."); // 切换到指定目录 ftpClient.changeWorkingDirectory(remoteDirPath); // 获取指定目录下的所有文件 FTPFile[] files = ftpClient.listFiles(); for (FTPFile file : files) { if (file.isFile()) { // 下载文件 downloadFile(ftpClient, file.getName(), localDirPath); } } // 登出FTP服务器 ftpClient.logout(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 下载文件 * @param ftpClient FTP客户端 * @param fileName 文件名 * @param localDirPath 本地目录路径 * @throws IOException */ private static void downloadFile(FTPClient ftpClient, String fileName, String localDirPath) throws IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(localDirPath + "/" + fileName); ftpClient.retrieveFile(fileName, fos); } finally { if (fos != null) { fos.close(); } } } } ``` 需要注意的是,上述代码使用了Apache Commons Net库来实现FTP操作,需要在项目中引用该库。可以从Apache官网下载该库或者通过Maven等构建工具添加依赖。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值