Java 连接FTP

连接FTP、获取文件、删除文件

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;

/**
 * 读取FTP server下文件
 * 
 */
public class FtpUtils {

	private static final Logger logger = Logger.getLogger(FtpUtils.class);
	/**
	 * @param ip
	 * @param port
	 * @param userName
	 * @param userPwd
	 * @param path
	 * @throws SocketException
	 * @throws IOException
	 *             function:连接到服务器
	 */
	public static FTPClient connectServer(String ip, int port, String userName,
			String userPwd, String path) {
		FTPClient ftpClient = new FTPClient();
		try {
			// 连接
			ftpClient.connect(ip, port);
			// 登录
			ftpClient.login(userName, userPwd);
			ftpClient.enterLocalPassiveMode();
			if (StringUtils.isNotEmpty(path)) {
				// 跳转到指定目录
				ftpClient.changeWorkingDirectory(path);
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.info("--------------ftp连接成功--------------");
		return ftpClient;
	}

	/**
	 * @throws IOException
	 *             function:关闭连接
	 */
	public static void closeServer(FTPClient ftpClient) {
		if (ftpClient.isConnected()) {
			try {
				ftpClient.logout();
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param path
	 * @return function:读取指定目录下的文件名
	 * @throws IOException
	 */
	public static List<String> getfilePathList(FTPClient ftpClient,String path) {
		List<String> fileNames = new ArrayList<String>();
		// 获得指定目录下所有文件名
		FTPFile[] ftpFiles = null;
		System.out.println(ftpClient);
		try {
			logger.info("--------下载文件的路径: "+path);
			ftpFiles = ftpClient.listFiles(path);
			logger.info("--------开始读取文件: " + ftpFiles);
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.info("---------文件个数: " + ftpFiles.length);
		for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
			FTPFile file = ftpFiles[i];
			if (file.isFile()) {
				logger.info("---------文件名称: " + file.getName());
				if (file.getName().endsWith(".tsv.zip")) {
					fileNames.add(file.getName());
				}
			}
		}
		return fileNames;
	}

	/**
	 * @Title: readFile   
	 * @Description: 从服务器上读取指定的文件 
	 * @param: @param ftpClient
	 * @param: @param fileName ftp上的文件名
	 * @param: @param filePath 本地地址
	 * @param: @return
	 * @param: @throws ParseException      
	 * @return: String      
	 * @throws
	 */
	public static boolean readFile(FTPClient ftpClient,String ftpFileName,String localFilePath) throws ParseException {
		boolean flag = false;
		InputStream ins = null;
		try {
			// 从服务器上读取指定的文件
			ins = ftpClient.retrieveFileStream(ftpFileName);
			File localFile = new File(localFilePath + ftpFileName);
			if(!localFile.exists()){
				localFile.getParentFile().mkdirs();
			}
			FileOutputStream fos=new FileOutputStream(localFile);
			byte[] buffer=new byte[10240];
            int size=0;
            while((size=ins.read(buffer))!=-1){
                fos.write(buffer, 0, size);
            }
            ins.close();
            fos.close();
			ftpClient.getReply();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("------下载文件失败--------"+e);
		}
		return flag;
	}

	/**
	 * @param filePath
	 *            function:删除文件
	 */
	public static void deleteFile(FTPClient ftpClient,String filePath) {
		try {
			ftpClient.deleteFile(filePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 * @throws ParseException
	 */
	public static void main(String[] args) throws ParseException {
		//01-cri-albanian_20171113-150000.tsv.gz
//		FtpUtils ftp = new FtpUtils();
//		FTPClient ftpClient = ftp.connectServer("ftp4.omniture.com", 21, "cridf","P.lt1Opn", "/");
//		ftp.getfilePathList(ftpClient, "/");
//		ftp.readFile(ftpClient,"01-cri-albanian_20171113-150000.tsv.gz","D://01-cri-albanian_20171113-150000.tsv.gz");
//		ftp.closeServer(ftpClient);
		System.out.println("成功");
	}
}

<think>我们正在回答用户关于如何使用Java连接FTP服务器的问题。根据引用内容,我们可以使用ApacheCommonsNet库中的FTPClient类来实现。步骤:1.导入必要的库(ApacheCommonsNet)2.创建FTPClient实例3.设置连接参数(服务器地址、端口、用户名、密码等)4.连接服务器并登录5.进行文件操作(上传、下载、目录操作等)6.断开连接注意:根据引用[3],我们还需要设置一些连接参数,如编码、超时时间等。示例代码将展示如何连接并登录FTP服务器,然后执行一个简单的操作(例如列出文件)并断开连接。由于引用中提到了设置字符编码、超时时间等,我们在代码中也会体现这些设置。同时,根据引用[4],我们还可以参考Jetty等,但这里我们专注于FTP连接,所以使用ApacheCommonsNet库。让我们编写示例代码:</think>### Java 连接 FTP 服务器指南 以下是使用 Java 连接 FTP 服务器的完整步骤和示例代码,基于 Apache Commons Net 库实现: #### 一、准备工作 1. **导入依赖库** 在 Maven 项目中添加依赖(非 Maven 项目需下载 [commons-net-3.9.0.jar](https://commons.apache.org/proper/commons-net/)): ```xml <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.9.0</version> </dependency> ``` #### 二、连接 FTP 服务器代码示例 ```java import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FtpConnectionExample { public static void main(String[] args) { FTPClient ftpClient = new FTPClient(); String server = "ftp.example.com"; int port = 21; String user = "your_username"; String password = "your_password"; try { // 1. 设置连接参数 ftpClient.setConnectTimeout(5000); // 连接超时5秒 ftpClient.setDataTimeout(10000); // 数据传输超时10秒 ftpClient.setControlEncoding("UTF-8"); // 设置字符编码[^3] // 2. 连接服务器 ftpClient.connect(server, port); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { throw new Exception("FTP服务器拒绝连接,响应码:" + replyCode); } // 3. 登录认证 if (!ftpClient.login(user, password)) { throw new Exception("FTP登录失败"); } // 4. 设置传输模式 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 二进制传输模式[^3] ftpClient.enterLocalPassiveMode(); // 被动模式(穿透防火墙) System.out.println("成功连接FTP服务器!"); // 示例操作:列出根目录文件 String[] files = ftpClient.listNames(); System.out.println("根目录文件列表:"); for (String file : files) { System.out.println(file); } } catch (Exception e) { e.printStackTrace(); } finally { // 5. 断开连接 try { if (ftpClient.isConnected()) { ftpClient.logout(); // 退出登录[^2] ftpClient.disconnect(); // 断开连接 } } catch (IOException e) { e.printStackTrace(); } } } } ``` #### 三、关键配置说明 1. **连接模式选择** - `enterLocalPassiveMode()`:被动模式(推荐),适用于客户端在防火墙后 - `enterLocalActiveMode()`:主动模式(服务器需开放数据端口) 2. **文件传输类型** ```java ftpClient.setFileType(FTP.ASCII_FILE_TYPE); // 文本文件 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 二进制文件(图片/压缩包等)[^3] ``` 3. **目录操作示例** ```java // 创建目录 ftpClient.makeDirectory("/new_folder"); // 切换目录 ftpClient.changeWorkingDirectory("/target_folder"); // 删除目录 ftpClient.removeDirectory("/empty_folder"); ``` #### 四、常见问题处理 1. **连接超时**:检查防火墙设置,确保端口21开放 2. **中文乱码**:确认服务器编码,尝试 `ftpClient.setControlEncoding("GBK")` 3. **传输失败**:检查传输模式(主动/被动)是否匹配网络环境 > **安全提示**:生产环境建议使用 **FTPS(FTP over SSL)** 或 **SFTP(SSH File Transfer Protocol)** 替代明文传输的FTP协议[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Karma's a Bitch

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

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

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

打赏作者

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

抵扣说明:

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

余额充值