java如何读取ftp上的文件
读取FTP文件的方法
使用Apache Commons Net库可以方便地实现FTP文件读取操作。需要添加以下依赖到项目中:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version>
</dependency>
基本连接与文件下载
建立FTP连接并下载文件到本地:
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("ftp.example.com", 21);
ftpClient.login("username", "password");
ftpClient.enterLocalPassiveMode();
FileOutputStream outputStream = new FileOutputStream("local_file.txt");
boolean success = ftpClient.retrieveFile("remote_file.txt", outputStream);
outputStream.close();
if (success) {
System.out.println("File downloaded successfully.");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
直接读取文件内容
不保存到本地,直接读取文件内容:
InputStream inputStream = ftpClient.retrieveFileStream("remote_file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
inputStream.close();
处理大文件
对于大文件建议使用缓冲读取:
InputStream inputStream = ftpClient.retrieveFileStream("large_file.txt");
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
// 处理读取到的数据
}
inputStream.close();
注意事项
确保设置正确的文件类型:
ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 二进制文件
// 或
ftpClient.setFileType(FTP.ASCII_FILE_TYPE); // 文本文件
使用被动模式通常能解决防火墙问题:
ftpClient.enterLocalPassiveMode();
处理完成后必须调用completePendingCommand:
ftpClient.completePendingCommand();






