FTP方式上传文件

本文介绍了如何使用FTP方式上传文件,包括在Maven项目中添加相关依赖和提供FTP工具类的简单实现,实测有效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FTP方式上传文件

话不多说,直接贴代码,亲测可用(目前只在maven工程中测试使用)

1. 在pom文件中添加依赖

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-web</artifactId>
	<version>4.3.12.RELEASE</version>
</dependency>
	
<!--FTP包-->
<dependency>
	<groupId>commons-net</groupId>
	<artifactId>commons-net</artifactId>
	<version>1.4.1</version>
</dependency>

2. FTP工具类

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.util.StringUtils;



public class FtpUtil {
	
	private final static Log log = LogFactory.getLog(FtpUtil.class);

	public static boolean copyFileToftp(String remoteFileName,
			String remoteFileDire, File file) throws Exception {
		InputStream iStream = null;
		// ftp地址
		String ipAddr = "192.168.7.239";
		// ftp端口
		Integer port = 21;
		// ftp用户
		String user = "Yangshuxin";
		// ftp用户密码
		String passWord = "000000";
		FTPClient ftpClient = connectServer( ipAddr,  port,  user,
				 passWord);
		try {
			try {
				CreateDirecroty(ftpClient, remoteFileDire);
				iStream = new FileInputStream(file);
				ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
				ftpClient.setControlEncoding("UTF-8");
				ftpClient.enterLocalPassiveMode();
				boolean result = ftpClient.storeFile(remoteFileName, iStream);
				if (!result) {
					throw new Exception("上传文件失败");
				}
				return result;
			} catch (IOException e) {
				throw new Exception("ioException", e);
			} finally {
				if (iStream != null) {
					closeServer(ftpClient);
					iStream.close();
				}
			}

		} catch (IOException e) {
			throw new Exception("close ioException", e);
		}
	}

	public static void CreateDirecroty(FTPClient ftpClient, String path)
			throws IOException {
		path = path.replaceAll("\\\\", "/");
		String[] strs = path.split("/");
		for (int i = 0; i < strs.length; i++) {
			String str = strs[i];
			if (!ftpClient.changeWorkingDirectory(str)) {
				ftpClient.makeDirectory(str);
			}
			if (StringUtils.hasText(str)) {
				changeDirectory(ftpClient, str);
			}
		}
	}

	// 路径转换
	private static boolean changeDirectory(FTPClient ftpClient, String path)
			throws IOException {
		return ftpClient.changeWorkingDirectory(path);
	}

	// 关闭连接
	public static void closeServer(FTPClient ftpClient) throws IOException {
		if (ftpClient.isConnected()) {
			ftpClient.logout();
			ftpClient.disconnect();
		}
	}

	// 连接ftp主机
	private static FTPClient connectServer(String ipAddr, Integer port, String user,
			String passWord) throws Exception {
		FTPClient ftpClient = new FTPClient();
		try {
			log.info("ip:" + ipAddr);
			int connectCount = 0;// FTP连接失败时,重试次数
			while (true) {
				try {
					ftpClient.connect(ipAddr, port);
					break;
				} catch (Exception e) {
					e.printStackTrace();
					connectCount++;
					// 如果重试连接次数超过3次,则直接返回ftp连接失败
					if (connectCount <= 3) {
						log.info("第【" + connectCount + "】次重新尝试FTP【" + ipAddr
								+ "】连接!");
						Thread.sleep(5000L);
					} else {
						throw new SocketException(e.getMessage());
					}
				}
			}
			ftpClient.login(user, passWord);

		} catch (SocketException e) {
			throw new Exception("FTP连接失败:(可能原因:【" + ipAddr
					+ "】主机FTP服务已关闭或者FTP配置有误!)\r\n详细错误:" + e.getMessage());
		} catch (IOException e) {
			throw new Exception("FTP连接失败:" + e.getMessage());
		} catch (Exception e) {
			throw new Exception("FTP连接失败:(可能原因:【" + ipAddr
					+ "】主机FTP服务已关闭或者FTP配置有误!)\r\n详细错误:" + e.getMessage());
		}
		return ftpClient;
	}
	
	public static void main(String[] args) {
		String remoteFileDire = "";
		String remoteFileName = "aaaa.txt";
		String filePath = "C:\\FileExchange\\FWF\\aaaa.txt";
		File file = new File(filePath);
		try {
			boolean flag = FtpUtil.copyFileToftp(remoteFileName, remoteFileDire, file);
			System.out.println(flag);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值