java 通过ftp读取某个路径下的所有文件内容
/ 设置文件传输模式为二进制。// 连接到FTP服务器。
·
package com.ftp.demo;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.*;
public class FtpDemo {
public static void main(String[] args) {
FTPClient ftpClient = new FTPClient();
String server = "url";
int port = 21;
String username = "user";
String password = "123";
try {
// 连接到FTP服务器
ftpClient.connect(server, port);
ftpClient.login(username, password);
// 设置文件传输模式为二进制
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if (ftpClient.getReplyCode() > 0) {
String dirs = "/filesync";
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(dirs);
FTPFile[] ftpFiles = ftpClient.listFiles();
for (int i = 0; i < ftpFiles.length; i++) {
FTPFile ftpFile = ftpFiles[i];
System.out.println(ftpFile.getName());
InputStream inputStream = ftpClient.retrieveFileStream(dirs + File.separator + ftpFile.getName());
if (inputStream == null) {
continue;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String s=null;
while ((s= reader.readLine())!=null){
System.out.println(s);
}
System.out.println("ftpFile.getName() end.");
inputStream.close();
reader.close();
ftpClient.completePendingCommand();
}
}
// 断开连接
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
maven依赖
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.8.0</version> </dependency>
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)