java如何读取ftp上的文件
使用 Apache Commons Net 读取 FTP 文件
下载并引入 Apache Commons Net 库到项目中。可以通过 Maven 添加依赖:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version>
</dependency>
创建 FTP 客户端并连接到服务器:
FTPClient ftpClient = new FTPClient();
ftpClient.connect("ftp.example.com", 21);
ftpClient.login("username", "password");
检查连接是否成功,切换到二进制传输模式:
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
ftpClient.disconnect();
throw new IOException("FTP server refused connection.");
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
读取远程文件内容到本地输出流:
String remoteFile = "/path/to/remote/file.txt";
OutputStream outputStream = new ByteArrayOutputStream();
boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
if (!success) {
throw new IOException("Failed to retrieve file.");
}
String fileContent = outputStream.toString();
使用 Java NIO 的 FTP 文件系统提供器
确保项目使用 Java 7 或更高版本。构建 URI 连接到 FTP 服务器:
URI uri = URI.create("ftp://username:password@ftp.example.com/path/to/file.txt");
FileSystem fs = FileSystems.newFileSystem(uri, Collections.emptyMap());
通过 NIO 方式读取文件内容:
Path ftpPath = fs.getPath("/file.txt");
List<String> lines = Files.readAllLines(ftpPath, StandardCharsets.UTF_8);
处理大文件的流式读取
对于大文件,使用缓冲读取方式避免内存问题:
InputStream inputStream = ftpClient.retrieveFileStream(remoteFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// 处理每一行
}
ftpClient.completePendingCommand();
错误处理和资源清理
确保在 finally 块中关闭连接和资源:
finally {
if (ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
// 记录日志
}
}
}
被动模式设置
某些防火墙环境下需要设置被动模式:
ftpClient.enterLocalPassiveMode();
超时设置
配置连接和数据传输超时:
ftpClient.setConnectTimeout(30000);
ftpClient.setDataTimeout(60000);






