在windows下写好的代码,下载测试通过,完全没有问题。一放到linux上就失败,ftpClient.listFiles();方法获取不到对应的数组,打印的长度总是0。

我也是第一次写这东西,后来一网友说试试remote被动模式,我不知道还和这个连接模式有关系......

原来只需要在创建连接对象的时候加上ftpClient.enterRemotePassiveMode();就Ok了;之前有网友说加ftpClient.enterLocalPassiveMode();我加上测试一下,然并卵。

关于这两者的区别我还没来得及弄清楚,有懂的朋友写到楼下吧。上代码了:


public static FTPClient initFtpClient(String ftpHost, String userName,
			String passWord, int port){
		FTPClient ftpClient = null;
		try {
			ftpClient = new FTPClient();
			//建立连接
			ftpClient.connect(ftpHost, port);
			//登录
			ftpClient.login(userName, passWord);
			if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
				logger.info("登录失败,用户名或密码错误!");
				ftpClient.disconnect();
			}else{
				//初始化
				ftpClient.enterRemotePassiveMode();
				ftpClient.setControlEncoding("utf-8");
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
				logger.info("连接成功!");
			}
		} catch (SocketException e) {
			e.printStackTrace();
			StaticVar.printExceptionInfo(logger, e);
		} catch (IOException e) {
			e.printStackTrace();
			StaticVar.printExceptionInfo(logger, e);
		}
		return ftpClient;
	}

public static synchronized int downFilesForFtp(String ftpHost, String userName,
			String passWord, int port, String ftpPath) throws IOException{
		int updateCount = 0;
		OutputStream os = null;
		FTPClient ftpClient = null;
		try {
			ftpClient = initFtpClient(ftpHost, userName, passWord, port);
			System.out.println("当前目录:"+ftpClient.printWorkingDirectory());
			ftpClient.changeWorkingDirectory(ftpPath);
			FTPFile[] files = ftpClient.listFiles();
			System.out.println(ftpPath+"下文件个数:"+files.length);
			for (int i = 0; i < files.length; i++) {
				String fileName = files[i].getName();
				//判断文件类型
				if (fileName.indexOf(".txt") < 0){
					continue;
				}
				//判断日志文件是否已存在,没有则创建
				String downLogPath =  StaticVar.DOWN_LOG_PATH+StaticVar.DOWN_LOG_NAME;
				File downLog = new File(downLogPath);
				if (downLog.exists()){
					//判断是否已经下载过
					if (isDown(files[i], downLogPath)){
						logger.info("文件:"+fileName+"已经下载过了!");
						continue;
					}else{
						updateCount++;
					}
				}else{
					downLog.createNewFile();
					updateCount++;
				}
				//没有则新建该目录
				FileUtil.newFolder(StaticVar.TEMP_PATH);
				String saveFilePath = StaticVar.TEMP_PATH + fileName;
				os = new FileOutputStream(new File(saveFilePath));
				boolean isDown = ftpClient.retrieveFile(fileName, os);
				//记录下载日志
				if (isDown){
					logger.info("文件:" +saveFilePath+ "下载成功!");
					FileUtil.newFolder(StaticVar.DOWN_LOG_PATH);
					String log = files[i].getName() + "&" + files[i].getSize() + "&" + DateUtil.getNowDate(DateUtil.yyyyMMddHHmmss);
					FileUtil.writeFile(downLogPath, log);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("文件列表获取失败!");
			StaticVar.printExceptionInfo(logger, e);
		}finally{
			if (null != os){
				os.flush();
				os.close();
			}
			closeConn(ftpClient);
		}
		return updateCount;
	}


Logo

更多推荐