FTP工具类

Java 操作ftp 的工具类 ,亲测有效 Java 操作ftp 的工具类。 阅读详情

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilter;
import org.apache.commons.net.ftp.FTPReply;

import app.cn.qtt.cmbase.system.CCrppLog4j;

public class FTPUtil {
	private static CCrppLog4j log = new CCrppLog4j(FTPUtil.class.getName());

	/**
	 * 关闭FTP连接
	 * 
	 * @param client
	 */
	public static void disconnect(FTPClient client) {
		final String xFunctionName = "disconnect";
		if (client != null && client.isConnected()) {
			try {
				log.debug("开始关闭FTP连接……");
				client.disconnect();
				log.debug("FTP连接关闭成功!");
			} catch (IOException e) {
				
				log.exception(xFunctionName, e);
			}
		}
	}

	/**
	 * 下载FTP文件_文件名与源一致
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 * @param fileName
	 * @param localPath
	 * @return
	 */
	public static boolean DownLoadFile(String url, int port, String username,
			String password, String remotePath, String fileName,
			String localPath) {
		final String xFunctionName = "DownLoadFile";
		log.begin(xFunctionName);
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.enterLocalPassiveMode();
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					File localFile = new File(localPath + "/" + ff.getName());

					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
				}
			}

			ftp.logout();
			success = true;
		} catch (IOException e) {
			log.exception(xFunctionName , e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
			log.end(xFunctionName);
		}
		
		return success;
	}

	/**
	 * 下载FTP文件_文件名按传入重命名
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 * @param fileName
	 * @param localPath
	 * @param localName
	 * @return
	 */
	public static boolean DownLoadFile(String url, int port, String username,
			String password, String remotePath, String fileName,
			String localPath, String localName) {
		final String xFunctionName = "DownLoadFile";
		log.begin(xFunctionName);
		
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);

			ftp.enterLocalPassiveMode();
			// InetAddress addr = InetAddress.getByName(url);
			// boolean mode = ftp.enterRemoteActiveMode(addr, 21);
			log.info("url:" + url + ",remotePath:" + remotePath + ",fileName:+"
					+ fileName + "localPath:" + localPath);

			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();

			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					File localFile = new File(localPath + "/" + localName);

					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
				}
			}

			ftp.logout();
			success = true;
		} catch (IOException e) {
			log.exception(xFunctionName, e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
			log.end(xFunctionName);
		}
		return success;
	}

	public static String DownLoadFileForFilter(String url, int port,
			String username, String password, String remotePath,
			String fileName, String localPath) {
		final String xFunctionName = "DownLoadFileForFilter";
		log.begin(xFunctionName);
		
		String downloadFileName = null;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);
			ftp.enterRemotePassiveMode();
			ftp.enterLocalPassiveMode();
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return null;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录

			FTPFile[] fs = ftp.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().startsWith(fileName)
						&& ff.getName().endsWith(".AVL")) {// TODO
															// 此处后缀写死了
					File localFile = new File(localPath + "/" + ff.getName());
					downloadFileName = ff.getName();
					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
				}
			}

			ftp.logout();
		} catch (Exception e) {
			log.exception(xFunctionName, e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
			log.end(xFunctionName);
		}

		return downloadFileName;
	}

	public static String DownLoadFileWithFilter(String url, int port,
			String username, String password, String remotePath,
			String fileName, String localPath, FTPFileFilter filter) {
		String downloadFileName = null;
		System.out.println("DownLoadFileForFilter执行开始");
		FTPClient ftp = new FTPClient();
		System.out.println("FTPClient ftp = new FTPClient()执行完毕");
		try {
			int reply;
			System.out.println("ftp.connect(url, port);");
			ftp.connect(url, port);
			ftp.enterRemotePassiveMode();
			ftp.enterLocalPassiveMode();
			System.out.println("ftp.connect(url, port);执行结束");
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			System.out.println("ftp.login(username, password);登录开始");
			ftp.login(username, password);// 登录
			System.out.println("ftp.login(username, password);登录结束");
			reply = ftp.getReplyCode();
			System.out.println("reply=" + reply);
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return null;
			}
			

			System.out.println("FTPFile[] fs = ftp.listFiles();开始执行");
			////
			FTPFile[] fs = ftp.listFiles(remotePath, filter);
			System.out.println("FTPFile[] fs = ftp.listFiles();执行结束");
			for (FTPFile ff : fs) {
				File localFile = new File(localPath + "/" + ff.getName());
				downloadFileName = ff.getName();
				OutputStream is = new FileOutputStream(localFile);
				ftp.retrieveFile(ff.getName(), is);
				is.close();
			}

			ftp.logout();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}

		return downloadFileName;
	}

	
	public static boolean removeFile(String url, int port, String username,
			String password, String remotePath, String fileName) {
		boolean flag = false;
		FTPClient ftpClient = new FTPClient();
		if (ftpClient != null) {
			try {
				int reply;
				ftpClient.connect(url, port);

				ftpClient.login(username, password);// 登录
				reply = ftpClient.getReplyCode();
				log.info("reply=" + reply);
				if (!FTPReply.isPositiveCompletion(reply)) {
					ftpClient.disconnect();
					return flag;
				}

				ftpClient.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
				// 删除文件
				flag = ftpClient.deleteFile(fileName);

				ftpClient.logout();
				flag = true;
			} catch (IOException e) {
				log.error(e.getMessage());
			} finally {
				if (ftpClient.isConnected()) {
					try {
						ftpClient.disconnect();
					} catch (IOException ioe) {
						log.error(ioe.getMessage());
					}
				}
			}
		}

		return flag;
	}

	public static boolean renameFile(String url, int port, String username,
			String password, String remotePath, String fileName,
			String newFileName) {
		boolean flag = false;
		FTPClient ftpClient = new FTPClient();
		if (ftpClient != null) {
			try {
				int reply;
				ftpClient.connect(url, port);

				ftpClient.login(username, password);// 登录
				reply = ftpClient.getReplyCode();
				log.info("reply=" + reply);
				if (!FTPReply.isPositiveCompletion(reply)) {
					ftpClient.disconnect();
					return flag;
				}

				ftpClient.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
				// 删除文件
				flag = ftpClient.rename(fileName, newFileName);

				ftpClient.logout();
				flag = true;
			} catch (IOException e) {
				log.error(e.getMessage());
			} finally {
				if (ftpClient.isConnected()) {
					try {
						ftpClient.disconnect();
					} catch (IOException ioe) {
						log.error(ioe.getMessage());
					}
				}
			}
		}

		return flag;
	}

	/**
	 * 下载FTP文件
	 * 
	 * @param hostName
	 * @param hostPort
	 * @param usr
	 * @param pwd
	 * @param remotefile
	 * @param localfile
	 * @param encode
	 * @return
	 * @throws IOException
	 */
	public static boolean DownLoadFileFromFtp(String hostName, int hostPort,
			String usr, String pwd, String remotefile, String localfile,
			String encode) throws Exception {
		boolean bl = false;
		FTPClient ftpc = null;
		FileOutputStream out = null;
		try {
			ftpc = new FTPClient();
			ftpc.setControlEncoding(encode);
			ftpc.connect(hostName, hostPort);
			ftpc.login(usr, pwd);
			out = new FileOutputStream(localfile);
			ftpc.retrieveFile(remotefile, out);
			bl = true;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (ftpc != null) {
					ftpc.logout();
					ftpc.disconnect();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return bl;
	}

	/**
	 * 从FTP服务器上下载文件
	 * 
	 * @param hostname
	 *            FTP服务器主机名
	 * @param port
	 *            FTP服务端口
	 * @param remoteDirectory
	 *            远程目录
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @param encoding
	 *            使用编码
	 * @param localDirectory
	 *            本地目录
	 * @param deepDownload
	 *            是否遍历下载
	 * @param needDelete
	 *            下载完成后是否删除服务器上的文件
	 * @return
	 */
	public static List<FTPOperationLog> downloadFiles(final String hostname,
			final int port, final String remoteDirectory,
			final String username, String password, final String encoding,
			final String localDirectory, final boolean deepDownload,
			final boolean needDelete) {
		List<FTPOperationLog> list = Collections.emptyList();
		try {
			list = new FTPDownloadTools(hostname, port, remoteDirectory,
					username, password, encoding, localDirectory, deepDownload,
					needDelete).downloadFiles();
		} catch (IOException e) {
			log.exception("downloadFiles", e);
		}
		return list;
	}

	/**
	 * 获取FTP远程目录名
	 * 
	 * @param path
	 * @return
	 */
	public static String getDirectoryFrom(String path) {
		if (StringUtils.indexOf(path, "/") == 0) {
			return getDirectoryFrom(path.substring(1, path.length()));
		}
		return path;
	}

	/**
	 * @param hostname
	 * @param port
	 * @param remoteDirectory
	 * @param username
	 * @param password
	 * @param encoding
	 * @param localDirectory
	 * @param traversal
	 * @param needDelete
	 * @return
	 */
	public static List<FTPOperationLog> uploadFiles(final String hostname,
			final int port, final String remoteDirectory,
			final String username, String password, final String encoding,
			final String localDirectory, final boolean traversal,
			final boolean needDelete) {
		List<FTPOperationLog> list = Collections.emptyList();
		try {
			list = new FTPUploadTools(hostname, port, remoteDirectory,
					username, password, encoding, localDirectory, traversal,
					needDelete).uploadFiles();
		} catch (IOException e) {
			log.exception("uploadFiles", e);
		}
		return list;
	}

	/**
	 * 通过APACHE包上传到FTP
	 * 
	 * @param hostName
	 * @param hostPort
	 * @param usr
	 * @param pwd
	 * @param srcfile
	 * @param destfile
	 * @param encode
	 * @return
	 */
	public static boolean uploadToFtpByApacheFtp(String hostName, int hostPort,
			String usr, String pwd, String srcfile, String destfile,
			String encode) {
		boolean bl = false;
		FTPClient ftpc = null;
		FileInputStream in = null;
		try {
			ftpc = new FTPClient();
			ftpc.setControlEncoding(encode);
			ftpc.connect(hostName, hostPort);
			ftpc.login(usr, pwd);
			in = new FileInputStream(srcfile);
			ftpc.storeFile(destfile, in);
			bl = true;
		} catch (Exception e) {
			e.printStackTrace();
			bl = false;
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (ftpc != null) {
					ftpc.logout();
					ftpc.disconnect();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return bl;
	}

	/**
	 * 通过APACHE包上传到FTP
	 * 
	 * @param hostName
	 * @param hostPort
	 * @param usr
	 * @param pwd
	 * @param srcfile
	 * @param destfile
	 * @param encode
	 * @return
	 */
	public static boolean mkDirectByApacheFtp(String hostName, int hostPort,
			String usr, String pwd, String pathname, String encode) {
		boolean bl = false;
		FTPClient ftpc = null;
		try {
			ftpc = new FTPClient();
			ftpc.setControlEncoding(encode);
			ftpc.connect(hostName, hostPort);
			ftpc.login(usr, pwd);
			bl = ftpc.makeDirectory(pathname);
		} catch (Exception e) {
			e.printStackTrace();
			bl = false;
		} finally {
			try {
				if (ftpc != null) {
					ftpc.logout();
					ftpc.disconnect();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return bl;
	}

//	/**
//	 * 通过sun自带方法上传到FTP
//	 * 
//	 * @param hostName
//	 * @param hostPort
//	 * @param usr
//	 * @param pwd
//	 * @param srcfile
//	 * @param destfile
//	 * @param isAscii
//	 * @return
//	 * @throws IOException
//	 */
//	public static boolean uploadToFtpServer(String hostName, int hostPort,
//			String usr, String pwd, String srcfile, String destfile,
//			boolean isAscii) throws IOException {
//		boolean bl = false;
//		FtpClient ftpc = null;
//		FileInputStream in = null;
//		FileOutputStream out = null;
//		try {
//			//ftpc = new FtpClient(hostName, hostPort);
//			ftpc = FtpClient.create(new InetSocketAddress(hostName, hostPort));
//			if (isAscii) {
//				ftpc.setAsciiType();
//			} else {
//				ftpc.setBinaryType();
//			}
//			ftpc.login(usr, null, pwd);
//			in = new FileInputStream(srcfile);
//			out = new FileOutputStream(destfile);
//			byte[] bt = new byte[1024];
//			while (in.read(bt) != -1) {
//				out.write(bt, 0, bt.length);
//			}
//			bl = true;
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			if (out != null) {
//				out.close();
//			}
//			if (in != null) {
//				in.close();
//			}
//			if (ftpc != null) {
//				ftpc.close();
//			}
//		}
//		return bl;
//	}

	/**
	 * 下载FTP文件_文件名与源一致
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 * @param fileName
	 * @param localPath
	 * @param bl_passive
	 * @return
	 */
	public static boolean DownLoadFile(String url, int port, String username,
			String password, String remotePath, String fileName,
			String localPath, boolean bl_passive) {
		final String xFunctionName = "DownLoadFile";
		log.begin(xFunctionName);
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			ftp.enterLocalPassiveMode();
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录

			// 由于北京FTP服务器日期设置成中文无法正常LISTFILE,临时用这种方式_Begin
			File localFile = null;
			OutputStream is = null;
			localFile = new File(localPath + "/" + fileName);
			is = new FileOutputStream(localFile);
			ftp.retrieveFile(fileName, is);
			is.close();
			// 由于北京FTP服务器日期设置成中文无法正常LISTFILE,临时用这种方式_End
			ftp.logout();
			success = true;
		} catch (IOException e) {
			log.exception(xFunctionName , e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
			
			log.end(xFunctionName);
		}
		return success;
	}

	public static boolean DownLoadFileV2(String url, int port, String username,
			String password, String remotePath, String fileName,
			String localPath, boolean bl_passive) {
		final String xFunctionName = "DownLoadFile";
		log.begin(xFunctionName);
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			// ftp.enterLocalPassiveMode();
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录

			// 由于北京FTP服务器日期设置成中文无法正常LISTFILE,临时用这种方式_Begin
			File localFile = null;
			OutputStream is = null;
			localFile = new File(localPath + "/" + fileName);
			is = new FileOutputStream(localFile);
			ftp.retrieveFile(fileName, is);
			is.close();
			// 由于北京FTP服务器日期设置成中文无法正常LISTFILE,临时用这种方式_End
			ftp.logout();
			success = true;
		} catch (IOException e) {
			log.exception(xFunctionName , e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
			
			log.end(xFunctionName);
		}
		return success;
	}
	
	public static void main(String[] args){
		FTPFile[] fs=FTPUtil.listFiles("127.0.0.1", 11600, "username", "password", "path");
		System.out.println(fs.length);
	}
	/**
	 * @title 获取指定远程目录中所有文件及文件夹
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 * @param fileName
	 * @param localPath
	 */
	public static FTPFile[] listFiles(String url, int port, String userName,
			String pwd, String remotePath) {
		final String xFunctionName = "listFiles";
		log.begin(xFunctionName);
		FTPClient ftp = new FTPClient();
		FTPFile[] fs = null;
		try {
			int reply;
			ftp.connect(url, port);
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(userName, pwd);// 登录
			//ftp.enterLocalPassiveMode();
			//ftp.enterRemotePassiveMode();
			reply = ftp.getReplyCode();
			log.info("reply" + reply);
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				log.info("disconnect!!!!!!!!!!!!");
				return null;
			}
			System.out.println("切换到远程目录"+remotePath+ftp.changeWorkingDirectory(remotePath));// 转移到FTP服务器目录
			fs = ftp.listFiles();
			log.info(fs.length > 1 ? fs[0].getName() : "没有文件");
			ftp.logout();
		} catch (IOException e) {
			fs = null;
			log.exception(xFunctionName, e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					log.exception(xFunctionName, ioe);
				}
			}
			log.end(xFunctionName);
		}
		return fs;
	}

	public static FTPFile[] listFilesWithFilter(String url, int port,
			String userName, String pwd, String remotePath, FTPFileFilter filter) {
		final String xFunctionName = "listFilesWithFilter";
		log.begin(xFunctionName);
		FTPClient ftp = new FTPClient();
		FTPFile[] fs = null;
		try {
			int reply;
			ftp.connect(url, port);
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(userName, pwd);// 登录
			ftp.enterLocalPassiveMode();
			// ftp.enterRemotePassiveMode();
			reply = ftp.getReplyCode();
			log.info("reply" + reply);
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				log.info("disconnect!!!!!!!!!!!!");
				return null;
			}
			//ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			// fs = ftp.listFiles();
			fs = ftp.listFiles(remotePath, filter);
			log.info(fs.length > 1 ? fs[0].getName() : "没有文件");
			ftp.logout();
		} catch (IOException e) {
			fs = null;
			log.exception(xFunctionName, e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					log.exception(xFunctionName, ioe);
				}
			}
			log.end(xFunctionName);
		}
		return fs;
	}

	/**
	 * @title 修改指定文件名字
	 * @param url
	 * @param port
	 * @param userName
	 * @param pwd
	 * @param remotePath
	 * @param newFileName新的文件名字
	 * @return
	 */
	public static boolean modifyFileName(String url, int port, String userName,
			String pwd, String remotePath, String fileName, String newFileName) {
		final String xFunctionName = "modifyFileName";
		log.begin(xFunctionName);
		
		FTPClient ftp = new FTPClient();
		boolean success = false;
		try {
			int reply;
			ftp.connect(url, port);
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(userName, pwd);// 登录
			// ftp.enterLocalPassiveMode();
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			log.info("重命名:" + ftp.rename(fileName, newFileName));

			ftp.logout();
			success = true;
		} catch (IOException e) {
			success = false;
			log.exception(xFunctionName, e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					log.exception(xFunctionName, ioe);
				}
			}
			log.end(xFunctionName);
		}
		return success;
	}

	/**
	 * 
	 * @param file
	 *            上传的文件或文件夹
	 * @throws Exception
	 */
	public static boolean upload(String url, int port, String userName,
			String pwd, String remotePath, File file) {
		String xFunctionName ="upload";
		log.begin(xFunctionName);
		FTPClient ftp = new FTPClient();
		boolean success = false;
		try {

			ftp.connect(url, port);
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(userName, pwd);// 登录
			ftp.enterLocalPassiveMode();//被动模式
			ftp.changeWorkingDirectory(remotePath);
			if (file.isDirectory()) {
				ftp.makeDirectory(file.getName());
				ftp.changeWorkingDirectory(file.getName());
				String[] files = file.list();
				for (int i = 0; i < files.length; i++) {
					File file1 = new File(file.getPath() + "\\" + files[i]);
					if (file1.isDirectory()) {
						upload(url, port, userName, pwd, remotePath, file);
						ftp.changeToParentDirectory();
					} else {
						File file2 = new File(file.getPath() + "\\" + files[i]);
						FileInputStream input = new FileInputStream(file2);
						ftp.storeFile(file2.getName(), input);
						input.close();
					}
				}
			} else {
				File file2 = new File(file.getPath());
				FileInputStream input = new FileInputStream(file2);
				ftp.storeFile(file2.getName(), input);
				input.close();
			}
			ftp.logout();
			success = true;
		} catch (IOException e) {
			success = false;
			log.exception(xFunctionName, e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					log.exception(xFunctionName, ioe);
				}
			}
			log.end(xFunctionName);
		}
		return success;
	}
	
	/**
	 * 
	 * @param file
	 *            上传的文件或文件夹
	 * @throws Exception
	 */
	public static boolean uploadByPassiveMode(String url, int port, String userName,
			String pwd, String remotePath, File file) {
		String xFunctionName ="upload";
		log.begin(xFunctionName);
		FTPClient ftp = new FTPClient();
		boolean success = false;
		try {

			ftp.connect(url, port);
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(userName, pwd);// 登录
			ftp.changeWorkingDirectory(remotePath);
			if (file.isDirectory()) {
				ftp.makeDirectory(file.getName());
				ftp.changeWorkingDirectory(file.getName());
				String[] files = file.list();
				for (int i = 0; i < files.length; i++) {
					File file1 = new File(file.getPath() + "\\" + files[i]);
					if (file1.isDirectory()) {
						upload(url, port, userName, pwd, remotePath, file);
						ftp.changeToParentDirectory();
					} else {
						File file2 = new File(file.getPath() + "\\" + files[i]);
						FileInputStream input = new FileInputStream(file2);
						ftp.storeFile(file2.getName(), input);
						input.close();
					}
				}
			} else {
				File file2 = new File(file.getPath());
				FileInputStream input = new FileInputStream(file2);
				log.info("ftp.storeFile(file2.getName(), input)方法调用开始。");
				ftp.storeFile(file2.getName(), input);
				log.info("ftp.storeFile(file2.getName(), input)方法调用结束。");
				input.close();
			}
			ftp.logout();
			success = true;
		} catch (Exception e) {
			success = false;
			log.exception(xFunctionName, e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					log.exception(xFunctionName, ioe);
				}
			}
			log.end(xFunctionName);
		}
		return success;
	}
	
	/**
	 * 下载FTP文件_文件名按传入重命名
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 * @param fileName
	 * @param localPath
	 * @param localName
	 * @return
	 */
	public static boolean downLoadFileByRetrive(String url, int port, String username,
			String password, String remotePath, String fileName,
			String localPath) {
		final String xFunctionName = "DownLoadFile";
		log.begin(xFunctionName);
		
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);

			ftp.enterLocalPassiveMode();
			// InetAddress addr = InetAddress.getByName(url);
			// boolean mode = ftp.enterRemoteActiveMode(addr, 21);
			log.info("url:" + url + ",remotePath:" + remotePath + ",fileName:+"
					+ fileName + "localPath:" + localPath);

			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			File localFile = new File(localPath + "/" + fileName);
			OutputStream is = new FileOutputStream(localFile);
			boolean result = ftp.retrieveFile(fileName, is);
			is.close();
			ftp.logout();
			success = result;
		} catch (IOException e) {
			log.exception(xFunctionName, e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
			log.end(xFunctionName);
		}
		return success;
	}
}

java ftp 上传下载文件 commons-net-1.2.2.jar java编程如何从ftp服务器上上传文件或下载文件 立即下载

相关推荐

微信小程序消息推送全攻略:从模板消息到订阅消息的实战避坑指南

本文深入解析微信小程序消息推送机制,对比模板消息、订阅消息与客服消息的核心差异与适用场景。重点提供订阅消息从用户授权设计、前端代码实现到后端稳定发送的完整实战指南,并分享提升消息点击率的文案与运营技巧,帮助开发者构建高效、用户友好的消息推送体系。

b3n4m5q6w7的博客 336

apache的org.apache.commons.net包 下载文件问题总结

<br />enterLocalActiveMode,enterRemoteActiveMode,enterRemotePassiveMode。<br />我的理解大概是这样的<br />enterLocalPassiveMode:设置客户端PASV模式<br />static int PASSIVE_LOCAL_DATA_CONNECTION_MODE<br />enterLocalActiveMode:设置客户端PORT模式<br />static int ACTIVE_LOCAL_DATA_CONNE

szl的专栏 5390

从零构建C++ Gerber解析器:以PCB缺陷检测为目标的实战指南

本文是一份面向PCB缺陷检测项目的实战指南,详细介绍了如何从零开始使用C++构建高性能的Gerber文件解析器。文章深入剖析了Gerber RS-274X格式,并提供了完整的开发环境搭建、核心数据结构设计、解析步骤实现以及为缺陷检测优化的具体方案,旨在帮助开发者获得对PCB制造数据的深度控制与极致性能。

weixin_29291185的博客 184

java中连接ftp服务器方法区别

enterLocalPassiveMode:设置客户端PASV模式 static int PASSIVE_LOCAL_DATA_CONNECTION_MODE enterLocalActiveMode:设置客户端PORT模式 static int ACTIVE_LOCAL_DATA_CONNECTION_MODE enterRemoteActiveMode:server to server...

可可飞扬的博客 1890

FPGA时序约束--实战篇(读懂Vivado时序报告)

本文将详细介绍如何读懂Vivado时序报告,包括报告的基本结构和如何分析报告。

mengzaishenqiu的博客 1万+

SRAM compiler选项中 Soft Error Repair (SER)

引起的瞬时故障,可能会影响 SRAM 中存储的数据。SER 功能通过某种机制检测并修复这些错误,从而提高存储器的可靠性。在 SRAM 编译器中,

hzmscut的博客 1154

ftp文件上传和下载

ftp参数实体 public class FTPParameter { private String host; private int port; private String user; private String pass; private String dir; //下载路径 private int mode; priva

少说,多做 2万+

Windows10内核逆向-2-KiSystemCall64的调用流程剖析

本文深入剖析了Windows 10 x64系统中KiSystemCall64函数的完整调用流程。从用户态触发syscall指令开始,详细讲解了如何通过swapgs切换内核栈、构建KTRAP_FRAME陷阱帧、进行SMAP/CFG等安全检查,到最终通过SSDT寻址并执行目标系统服务的全过程,揭示了系统调用从Ring 3到Ring 0切换的核心机制与安全设计。

weixin_29209805的博客 82

commons-ftp中ftpClient类的API(构造方法)

Constructor Summary 构造方法摘要 FTPClient ()  Default FTPClient constructor.默认FTPClient构造。   Method Summary 方法摘要 protected void _connectAction_ () 

ypyying2010的专栏 2583

【AI工具】Browser use搭建及使用的保姆级教程:让AI帮你自动操作浏览器

【AI工具】Browser use搭建及使用的保姆级教程:让AI帮你自动操作浏览器

funfan的博客 2535

(五)C++自制植物大战僵尸游戏LoadingScene的实现讲解

游戏启动后就会立即切换到游戏加载场景中。只有游戏资源文件加载完成后,才能进入游戏。Loadingscene类继承Cocos2d-x中的Scene父类,表明Loadingscene是一个场景类。切换到LoadingScene场景中,首先会创建该场景,会调用函数,在该函数中调用自己定义的方法实现指定功能。代码文件的位置如下图所示。

尔灵尔亿的博客 2006

springboot-ftp

springboot-ftp代码展示端口模式 代码展示 springboot:2.1.4.RELEASE java:1.8 ftp在远程局域网linux服务器,调用客户端在win电脑。 依赖 <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <v

没啥简介 3029

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

FTP 工具类

xtype: 'datefield', fieldLabel: '* 出院时间', name: 'outdate', id: 'outdate', anchor: '97%', allowBlank:

——不言而喻 618

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

ftp工具类

package com.common.utils.ftpUtils; import com.common.utils.EmptyUtils; import com.common.utils.MyPropertiesUtils; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFi...

纳川的博客 605

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

Java Ftp上传文件,Ftp工具类

这里已经忘了参考的哪位博友的文章,如果有哪位小伙伴看到,请留言Ftp工具类package com.ldl.test.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.Fil...

Liam1994的博客 1397

java ftp 工具类

java ftp工具类,参考不知道哪位大神写得工具类(现在找不到链接了),后来自己修改了部分代码,单例模式,封装了查询文件夹是否存在、创建文件夹、上传文件、下载文件、删除文件等方法,经试验可用。 需要自己创建一个config的property文件。里面需要有文档中写出的几个属性。

殷长庆的博客 1213

C# FTP工具类

C# FTP工具类 许多博客提供的ftp工具类中,方法被调时需要先移动ftp服务器当前所在目录,并且存在bug,非常不爽。本人加以改动,符合调用习惯,并经过实际项目测试。 FTP工具类代码 /// <summary> /// Ftp工具类 /// </summary> public class FtpHelper { ...

Superman安安的博客 648

Java FTP工具类

因工作需要,需要在后台处理一些小文件,比如网页资源到服务器上保存,本来计划使用DFS来进行压缩存储,考虑到需要再次解压生成访问连接,暂时先直接通过FTP直接保存在服务器上。就看了下Java下的ftp上传的实现方法,参照了网上的代码。 这里给出我封装的一个工具类,可以直接使用,应该需要再优化。 使用了Apache的commons-net-1.4.1.jar开源组件。 对应的API地址如下: h

hnxydq的专栏 9069

FTP工具类(ftp4j)

package com.cb.commons.util; import it.sauronsoftware.ftp4j.FTPClient; import it.sauronsoftware.ftp4j.FTPException; import it.sauronsoftware.ftp4j.FTPFile; import java.io.File; import java.net.URL; /** * FTP文件处理工具类 * * @author Johnson * @ver

灵魂在奔跑 1万+

手写一个好用的Java FTP操作工具类

前言 网上百度了很多FTP的java 工具类,发现文章代码都比较久远,且代码臃肿,即使搜到了代码写的还可以的,封装的常用操作方法不全面,于是自己花了半天实现一个好用的工具类。最初想用java自带的FTPClient 的jar 去封装,后来和apache的jar工具包对比后,发现易用性远不如apache,于是决定采用apache的ftp的jar 封装ftp操作类。 之前写过一篇 windows 服务器搭建FTP服务的教程 点击查看 代码展示 pom文件引入依赖关系 commons-net...

洛阳泰山的博客 2487

ftp上传下载工具类

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.OutputStrea...

weixin_34117522的博客 98
上一篇: 读取excel保存数据库
下一篇: jsp倒计时分秒
丵鹰
博客等级 码龄15年 37粉丝 50原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丵鹰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值