`

Java的ftp上传下载工具

    博客分类:
  • java
 
阅读更多

 

自己写的利用apache的net包写的ftp的上传、下载功能,可以上单个文件、文件夹,下载单个文件及文件夹整个目录,并且解决了文件、文件夹汉字问题,经过自己的正式测试。

        不讲废话了,直接上代码,愿给需要的朋友提供个帮助。

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.d6.utils.AppUtils;

/**
 * @author jjl
 * 
 */
public class FtpUtil {
	static String ftpUrl = null; // ftp 服务器路径
	static int ftpPort = 21; // ftp 服务器端口
	static String ftpUserName = null; // ftp 服务器用户名
	static String ftpPassword = null; // ftp 服务器密码
	static String encoding = null;
	static String serverLanguageCode = FTP.DEFAULT_CONTROL_ENCODING;
	static int timeout = 60000;
	// 配置文件路径
	static String configFile =  "ftp.properties";

	static FTPClient ftpClient = null;

	/**
	 * 创建FTPClient
	 * 
	 * @throws Exception
	 */
	private static void createFtpClient() throws Exception {
		if (ftpClient == null) {
			ftpClient = new FTPClient();
			setConnectConfig();
			connectFtp(ftpClient);
		}
	}

	/**
	 * 关闭FTPClient
	 * 
	 * @throws Exception
	 */
	private static void closeFtpClient() throws Exception {
		if (ftpClient != null) {
			ftpClient.logout();
			if (ftpClient.isConnected()) {
				ftpClient.disconnect();
			}
			ftpClient = null;
		}
	}

	/**
	 * ftp工具连接
	 * 
	 * @param ftpClient
	 * @return
	 * @throws Exception
	 */
	public static boolean connectFtp(FTPClient ftpClient) throws Exception {
		// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
		ftpClient.connect(ftpUrl, ftpPort);
		
		getFtpConfig();

		// 返回登录情况
		boolean isConnect = ftpClient.login(ftpUserName, ftpPassword);

		ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
		// ftpClient.enterLocalPassiveMode();
		ftpClient.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
		ftpClient.setControlEncoding(encoding);
		
		// 设置连接时间
		ftpClient.setDataTimeout(timeout);
		// 返回代码
		int reply = ftpClient.getReplyCode();
		if (isConnect && FTPReply.isPositiveCompletion(reply)) {
			return true;
		}
		return false;
	}

	/**
	 * 上传文件
	 * 
	 * @param localPath
	 *            本地文件路径
	 * @param filename
	 *            本地文件名
	 * @param remotePath
	 *            服务器文件路径
	 * @return 成功返回true,否则返回false
	 * @throws Exception
	 */
	public static boolean uploadFile(File file, String remotePath)
			throws Exception {
		boolean success = false;

		try {
			// 创建FTPClient
			createFtpClient();

			// 判断是文件,还是文件目录
			if (file.isDirectory()) {
				success = uploadAll(file, remotePath + File.separator
						+ file.getName());
			} else {
				success = upload(file, remotePath);
			}

			// 关闭连接
			closeFtpClient();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 返回
		return success;
	}

	/**
	 * 上传文件
	 * 
	 * @param file
	 * @param remotePath
	 * @return
	 * @throws Exception
	 */
	private static boolean upload(File file, String remotePath)
			throws Exception {
		boolean success;
		// 文件
		FileInputStream inputStream = new FileInputStream(file);
		// 切换ftp工作目录
		changeWorkingDirectory(remotePath);

		// 上传文件
		success = ftpClient.storeFile(encodingGBKToISO8859(file.getName()),
				inputStream);

		inputStream.close();
		return success;
	}

	/**
	 * 上传文件
	 * 
	 * @param localPath
	 *            本地文件路径
	 * @param filename
	 *            本地文件名
	 * @param remotePath
	 *            服务器文件路径
	 * @return
	 * @throws Exception
	 */
	public static boolean uploadFile(String localPath, String filename,
			String remotePath) throws Exception {
		File file = new File(localPath + File.separator + filename);
		return uploadFile(file, remotePath);
	}

	/**
	 * 上传文件目录
	 * 
	 * @param file
	 * @param remotePath
	 * @return
	 * @throws Exception
	 */
	public static boolean uploadDirectory(String localPath, String remotePath)
			throws Exception {
		return uploadDirectory(new File(localPath), remotePath);
	}

	/**
	 * 上传文件目录
	 * 
	 * @param file
	 * @param remotePath
	 * @return
	 * @throws Exception
	 */
	public static boolean uploadDirectory(File file, String remotePath)
			throws Exception {
		boolean success = false;
		// 创建FTPClient
		createFtpClient();

		success = uploadAll(file, remotePath);

		// 关闭连接
		closeFtpClient();
		return success;
	}

	/**
	 * 上传
	 * 
	 * @param file
	 * @param remotePath
	 * @throws Exception
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static boolean uploadAll(File file, String remotePath)
			throws Exception {
		boolean success = false;
		// 得到文件列表
		File[] fileList = file.listFiles();
		for (File uploadFile : fileList) {
			// 循环子目录
			if (uploadFile.isDirectory()) {
				ftpClient.changeWorkingDirectory(remotePath);
				ftpClient.makeDirectory(uploadFile.getName());
				success = uploadAll(uploadFile, remotePath + File.separator
						+ uploadFile.getName());
			} else {
				// 上传文件
				success = upload(uploadFile, remotePath);
			}
		}
		return success;
	}

	/**
	 * 下载文件目录下所有文件
	 * 
	 * @param localPath
	 *            本地文件路径
	 * @param fileName
	 *            本地文件名
	 * @param remotePath
	 *            服务器路径
	 * @return 成功返回true,否则返回false
	 * @throws Exception
	 */
	public static boolean downloadDirectory(String localPath, String remotePath)
			throws Exception {
		boolean success = false;

		try {
			// 创建FTPClient
			createFtpClient();

			success = downloadAll(localPath, remotePath);

			// 关闭连接FTPClient
			closeFtpClient();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return success;
	}

	/**
	 * 下载文件目录下的所有文件
	 * 
	 * @param localPath
	 * @param remotePath
	 * @param success
	 * @return
	 * @throws IOException
	 * @throws Exception
	 * @throws FileNotFoundException
	 */
	private static boolean downloadAll(String localPath, String remotePath)
			throws Exception {
		boolean success = false;

		// 切换ftp工作目录
		changeWorkingDirectory(remotePath);
		// 取出下载文件
		FTPFile[] ftpFiles = ftpClient.listFiles();
		for (FTPFile ftpFile : ftpFiles) {
			// 过滤文件名不正确的文件
			if (ftpFile.getName().equals(".") || ftpFile.getName().equals("..")) {
				continue;
			}
			if (ftpFile.isDirectory()) {
				// 创建目录
				File fileDir = new File(localPath + File.separator
						+ ftpFile.getName());
				if (!fileDir.exists()) {
					fileDir.mkdirs();
				}
				// 下载文件
				success = downloadAll(localPath + File.separator
						+ ftpFile.getName(), remotePath + File.separator
						+ ftpFile.getName());
			} else {
				// 切换ftp工作目录
				changeWorkingDirectory(remotePath);
				// 下载文件
				success = download(localPath, ftpFile);
			}
		}
		return success;
	}

	/**
	 * 切换ftp工作目录
	 * 
	 * @param remotePath
	 * @throws IOException
	 */
	private static void changeWorkingDirectory(String remotePath)
			throws IOException {
		// 转移到FTP服务器目录
		ftpClient.changeWorkingDirectory("/");
		if (StringUtils.isNotBlank(remotePath)) {
			ftpClient.changeWorkingDirectory(remotePath);
		}
	}

	/**
	 * @param localPath
	 * @param ftpFile
	 * @return
	 * @throws Exception
	 */
	private static boolean download(String localPath, FTPFile ftpFile)
			throws Exception {
		boolean success;
		// 文件目录不存在创建文件
		File fileDir = new File(localPath);
		if (!fileDir.exists()) {
			fileDir.mkdirs();
		}

		File localFile = new File(localPath + File.separator
				+ ftpFile.getName());

		OutputStream is = new FileOutputStream(localFile);
		// 下载文件
		success = ftpClient.retrieveFile(
				encodingGBKToISO8859(ftpFile.getName()), is);
		is.close();
		return success;
	}

	/**
	 * 下载文件
	 * 
	 * @param localPath
	 *            本地文件路径
	 * @param fileName
	 *            本地文件名
	 * @param remotePath
	 *            服务器路径
	 * @return 成功返回true,否则返回false
	 * @throws Exception
	 */
	public static boolean downloadFile(String localPath, String fileName,
			String remotePath) throws Exception {
		boolean success = false;

		try {
			// 创建FTPClient
			createFtpClient();

			// 转移到FTP服务器目录
			if (StringUtils.isNotBlank(remotePath)) {
				ftpClient.changeWorkingDirectory(remotePath);
			}

			// 取出下载文件
			FTPFile[] ftpFiles = ftpClient.listFiles();
			for (FTPFile ftpFile : ftpFiles) {
				String ftpFileName = ftpFile.getName();
				if (ftpFileName.equals(fileName)) {
					success = download(localPath, ftpFile);
					break;
				}
			}

			// 关闭连接FTPClient
			closeFtpClient();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return success;
	}

	/**
	 * 删除一个文件
	 * 
	 * @throws Exception
	 */
	public static boolean deleteFile(String filename) throws Exception {
		boolean flag = true;
		try {
			// 创建FTPClient
			createFtpClient();
			// 删除文件
			flag = ftpClient.deleteFile(filename);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			// 关闭连接FTPClient
			closeFtpClient();
		}

		return flag;
	}

	/**
	 * 删除目录
	 * 
	 * @throws Exception
	 */
	public static void deleteDirectory(String pathname) throws Exception {
		try {
			// 创建FTPClient
			createFtpClient();
			File file = new File(pathname);
			if (!file.isDirectory()) {
				deleteFile(pathname);
			}
			ftpClient.removeDirectory(pathname);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			// 关闭连接FTPClient
			closeFtpClient();
		}
	}

	/**
	 * 设置参数
	 * 
	 * @param configFile
	 *            --参数的配置文件
	 */
	private static void setConnectConfig() {
		Properties property = new Properties();
		BufferedInputStream bis = null;
		try {
			// 读取配置文件
			File file = new File(configFile);
			bis = new BufferedInputStream(new FileInputStream(file));
			property.load(bis);

			// 设置文件信息
			ftpUserName = property.getProperty("ftp.userName");
			ftpPassword = property.getProperty("ftp.password");
			ftpUrl = property.getProperty("ftp.url");
			ftpPort = Integer.parseInt(property.getProperty("ftp.port"));
			encoding = property.getProperty("ftp.encoding");
			serverLanguageCode = property.getProperty("ftp.serverLanguageCode");

			// 关闭文件
			if (bis != null){
				bis.close();
			}
		} catch (FileNotFoundException e1) {
			System.out.println("配置文件 " + configFile + " 不存在!");
		} catch (IOException e) {
			System.out.println("配置文件 " + configFile + " 无法读取!");
		}
	}

	/**
	 * 重命名文件
	 * 
	 * @param oldName
	 *            原文件名
	 * @param newName
	 *            新文件名
	 * @throws Exception
	 */
	public static void renameFile(String oldName, String newName)
			throws Exception {
		try {
			// 创建FTPClient
			createFtpClient();

			// 重命名
			ftpClient.rename(oldName, newName);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			// 关闭连接FTPClient
			closeFtpClient();
		}
	}

	/**
	 * 设置FTP客服端的配置
	 * 
	 * @return ftpConfig
	 */
	private static FTPClientConfig getFtpConfig() {
		// FTPClientConfig.SYST_UNIX
		FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_NT);
		ftpConfig.setServerLanguageCode(serverLanguageCode);
		return ftpConfig;
	}

	/**
	 * 将ISO-8859-1编码转为 GBK
	 * 
	 * @param obj
	 * @return ""
	 * @throws Exception
	 */
	private static String encodingToGBK(Object obj) throws Exception {
		if (obj != null) {
			return new String(obj.toString().getBytes("iso-8859-1"), encoding);
		}
		return null;
	}

	/**
	 * 将 GBK编码转为ISO-8859-1
	 * 
	 * @param obj
	 * @return ""
	 * @throws Exception
	 */
	private static String encodingGBKToISO8859(Object obj) throws Exception {
		if (obj != null) {
			return new String(obj.toString().getBytes(encoding), "iso-8859-1");
		}
		return null;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		boolean success = false;
		try {
			java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//			success = FtpUtil.uploadFile("D:\\ftp", "中文的.docx", "temp");
//			System.out.println(success);
			//
			// success = FtpUtil.uploadFile(new File("D:\\ftp\\abc.txt"),
			// "temp");
			// System.out.println(success);

			// success = FtpUtil.uploadDirectory("D:\\ftp", "temp");
			// System.out.println(success);

			System.out.println(dateFormat.format(new java.util.Date()));
			success = FtpUtil.downloadFile("d:\\", "test.zip",
					"temp");
			System.out.println(dateFormat.format(new java.util.Date()));
			System.out.println(success);

			// success = FtpUtil.downloadDirectory("d:\\ftp\\a2", "temp");
			// System.out.println(success);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

	}

}
 

 

分享到:
评论

相关推荐

    避开10大常见坑:DeepSeekAPI集成中的错误处理与调试指南.pdf

    在日常的工作和学习中,你是否常常为处理复杂的数据、生成高质量的文本或者进行精准的图像识别而烦恼?DeepSeek 或许就是你一直在寻找的解决方案!它以其高效、智能的特点,在各个行业都展现出了巨大的应用价值。然而,想要充分发挥 DeepSeek 的优势,掌握从入门到精通的知识和技能至关重要。本文将从实际应用的角度出发,为你详细介绍 DeepSeek 的基本原理、操作方法以及高级技巧。通过系统的学习,你将能够轻松地运用 DeepSeek 解决实际问题,提升工作效率和质量,让自己在职场和学术领域脱颖而出。现在,就让我们一起开启这场实用又高效的学习之旅吧!

    前端分析-2023071100789

    前端分析-2023071100789

    基于kinect的3D人体建模C++完整代码.cpp

    基于kinect的3D人体建模C++完整代码.cpp

    搞机工具箱10.1.0.7z

    搞机工具箱10.1.0.7z

    GRU+informer时间序列预测(Python完整源码和数据)

    GRU+informer时间序列预测(Python完整源码和数据),python代码,pytorch架构,适合各种时间序列直接预测。 适合小白,注释清楚,都能看懂。功能如下: 代码基于数据集划分为训练集测试集。 1.多变量输入,单变量输出/可改多输出 2.多时间步预测,单时间步预测 3.评价指标:R方 RMSE MAE MAPE,对比图 4.数据从excel/csv文件中读取,直接替换即可。 5.结果保存到文本中,可以后续处理。 代码带数据,注释清晰,直接一键运行即可,适合新手小白。

    性价比革命:DeepSeekAPI成本仅为GPT-4的3%的技术揭秘.pdf

    在日常的工作和学习中,你是否常常为处理复杂的数据、生成高质量的文本或者进行精准的图像识别而烦恼?DeepSeek 或许就是你一直在寻找的解决方案!它以其高效、智能的特点,在各个行业都展现出了巨大的应用价值。然而,想要充分发挥 DeepSeek 的优势,掌握从入门到精通的知识和技能至关重要。本文将从实际应用的角度出发,为你详细介绍 DeepSeek 的基本原理、操作方法以及高级技巧。通过系统的学习,你将能够轻松地运用 DeepSeek 解决实际问题,提升工作效率和质量,让自己在职场和学术领域脱颖而出。现在,就让我们一起开启这场实用又高效的学习之旅吧!

    基于ANSYS LSDyna的DEM-SPH-FEM耦合模拟滑坡入水动态行为研究,基于ANSYS LSDyna的DEM-SPH-FEM耦合的滑坡入水模拟分析研究,基于ansys lsdyna的滑坡入水

    基于ANSYS LSDyna的DEM-SPH-FEM耦合模拟滑坡入水动态行为研究,基于ANSYS LSDyna的DEM-SPH-FEM耦合的滑坡入水模拟分析研究,基于ansys lsdyna的滑坡入水模拟dem-sph-fem耦合 ,基于ANSYS LSDyna; 滑坡入水模拟; DEM-SPH-FEM 耦合,基于DEM-SPH-FEM耦合的ANSYS LSDyna滑坡入水模拟

    auto_gptq-0.6.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

    auto_gptq-0.6.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

    复件 复件 建设工程可行性研究合同[示范文本].doc

    复件 复件 建设工程可行性研究合同[示范文本].doc

    13考试真题最近的t64.txt

    13考试真题最近的t64.txt

    Microsoft Visual C++ 2005 SP1 Redistributable PackageX86

    好用我已经解决报错问题

    嵌入式开发入门:用C语言点亮LED灯的全栈开发指南.pdf

    # 踏入C语言的奇妙编程世界 在编程的广阔宇宙中,C语言宛如一颗璀璨恒星,以其独特魅力与强大功能,始终占据着不可替代的地位。无论你是编程小白,还是有一定基础想进一步提升的开发者,C语言都值得深入探索。 C语言的高效性与可移植性令人瞩目。它能直接操控硬件,执行速度快,是系统软件、嵌入式开发的首选。同时,代码可在不同操作系统和硬件平台间轻松移植,极大节省开发成本。 学习C语言,能让你深入理解计算机底层原理,培养逻辑思维和问题解决能力。掌握C语言后,再学习其他编程语言也会事半功倍。 现在,让我们一起开启C语言学习之旅。这里有丰富教程、实用案例、详细代码解析,助你逐步掌握C语言核心知识和编程技巧。别再犹豫,加入我们,在C语言的海洋中尽情遨游,挖掘无限可能,为未来的编程之路打下坚实基础!

    auto_gptq-0.4.2-cp38-cp38-win_amd64.whl

    auto_gptq-0.4.2-cp38-cp38-win_amd64.whl

    自动立体库设计方案.pptx

    自动立体库设计方案.pptx

    手把手教你用C语言实现贪吃蛇游戏:从算法设计到图形渲染.pdf

    # 踏入C语言的奇妙编程世界 在编程的广阔宇宙中,C语言宛如一颗璀璨恒星,以其独特魅力与强大功能,始终占据着不可替代的地位。无论你是编程小白,还是有一定基础想进一步提升的开发者,C语言都值得深入探索。 C语言的高效性与可移植性令人瞩目。它能直接操控硬件,执行速度快,是系统软件、嵌入式开发的首选。同时,代码可在不同操作系统和硬件平台间轻松移植,极大节省开发成本。 学习C语言,能让你深入理解计算机底层原理,培养逻辑思维和问题解决能力。掌握C语言后,再学习其他编程语言也会事半功倍。 现在,让我们一起开启C语言学习之旅。这里有丰富教程、实用案例、详细代码解析,助你逐步掌握C语言核心知识和编程技巧。别再犹豫,加入我们,在C语言的海洋中尽情遨游,挖掘无限可能,为未来的编程之路打下坚实基础!

    性能对决:DeepSeek-V3与ChatGPTAPI在数学推理场景的基准测试.pdf

    在日常的工作和学习中,你是否常常为处理复杂的数据、生成高质量的文本或者进行精准的图像识别而烦恼?DeepSeek 或许就是你一直在寻找的解决方案!它以其高效、智能的特点,在各个行业都展现出了巨大的应用价值。然而,想要充分发挥 DeepSeek 的优势,掌握从入门到精通的知识和技能至关重要。本文将从实际应用的角度出发,为你详细介绍 DeepSeek 的基本原理、操作方法以及高级技巧。通过系统的学习,你将能够轻松地运用 DeepSeek 解决实际问题,提升工作效率和质量,让自己在职场和学术领域脱颖而出。现在,就让我们一起开启这场实用又高效的学习之旅吧!

    从零到一:手把手教你用Python调用DeepSeekAPI的完整指南.pdf

    在日常的工作和学习中,你是否常常为处理复杂的数据、生成高质量的文本或者进行精准的图像识别而烦恼?DeepSeek 或许就是你一直在寻找的解决方案!它以其高效、智能的特点,在各个行业都展现出了巨大的应用价值。然而,想要充分发挥 DeepSeek 的优势,掌握从入门到精通的知识和技能至关重要。本文将从实际应用的角度出发,为你详细介绍 DeepSeek 的基本原理、操作方法以及高级技巧。通过系统的学习,你将能够轻松地运用 DeepSeek 解决实际问题,提升工作效率和质量,让自己在职场和学术领域脱颖而出。现在,就让我们一起开启这场实用又高效的学习之旅吧!

    为什么你的switch总出bug?90%新手不知道的break语句隐藏规则.pdf

    # 踏入C语言的奇妙编程世界 在编程的广阔宇宙中,C语言宛如一颗璀璨恒星,以其独特魅力与强大功能,始终占据着不可替代的地位。无论你是编程小白,还是有一定基础想进一步提升的开发者,C语言都值得深入探索。 C语言的高效性与可移植性令人瞩目。它能直接操控硬件,执行速度快,是系统软件、嵌入式开发的首选。同时,代码可在不同操作系统和硬件平台间轻松移植,极大节省开发成本。 学习C语言,能让你深入理解计算机底层原理,培养逻辑思维和问题解决能力。掌握C语言后,再学习其他编程语言也会事半功倍。 现在,让我们一起开启C语言学习之旅。这里有丰富教程、实用案例、详细代码解析,助你逐步掌握C语言核心知识和编程技巧。别再犹豫,加入我们,在C语言的海洋中尽情遨游,挖掘无限可能,为未来的编程之路打下坚实基础!

    用deepseek变现实操流程

    用deepseek变现实操流程,小白必看。

    10个必知的DeepSeekAPI调用技巧:从鉴权到限流全解析.pdf

    在日常的工作和学习中,你是否常常为处理复杂的数据、生成高质量的文本或者进行精准的图像识别而烦恼?DeepSeek 或许就是你一直在寻找的解决方案!它以其高效、智能的特点,在各个行业都展现出了巨大的应用价值。然而,想要充分发挥 DeepSeek 的优势,掌握从入门到精通的知识和技能至关重要。本文将从实际应用的角度出发,为你详细介绍 DeepSeek 的基本原理、操作方法以及高级技巧。通过系统的学习,你将能够轻松地运用 DeepSeek 解决实际问题,提升工作效率和质量,让自己在职场和学术领域脱颖而出。现在,就让我们一起开启这场实用又高效的学习之旅吧!

Global site tag (gtag.js) - Google Analytics