在Java开发过程中,有些时候可能会遇到解析FTP中文件的问题,在此我们以txt格式为例子,来进行一次对FTP的访问。
首先是对一个文件的解析,我们使用properties文件来存储对访问FTP的一些基本配置:
如果FTP不需要账户密码的话,默认是anonymous;ftpHost为FTP地址。
//读取配置文件
InputStream propertiesIn = getClass().getClassLoader().getResourceAsStream(ftpConfigName + ".properties");
if (propertiesIn == null) {
logger.info("配置文件读取失败");
}
- 然后将配置文件中的基本信息一一获取:
String ftpUserName = properties.getProperty("ftpUserName");
String ftpPassword = properties.getProperty("ftpPassword");
String ftpHost = properties.getProperty("ftpHost");
String fileName = properties.getProperty("fileName");
String filePath = properties.getProperty("filePath");
- 连接服务器,跳转至操作路径:
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ftpHost);
ftpClient.login(ftpUserName, ftpPassword);
ftpClient.changeWorkingDirectory(filePath);
} catch (IOException e) {
e.printStackTrace();
}
- 获取该路径下的目录,与数据文件中一一比对
FTPFile[] file = new FTPFile[0];
try {
file = ftpClient.listFiles();
} catch (IOException e) {
logger.error("获取路径出错");
e.printStackTrace();
}
- 遍历比对:
for (int i = 0; i < file.length; i++) {
String name = file[i].getName();
if (fileName.equals(name)) {
try (InputStream in = ftpClient.retrieveFileStream(name)) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
ftpClient.completePendingCommand();//完成挂起。可重复读取
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
}
}
- 如果是对该文件夹下所有的文件进行解析,则可以跳过比对步骤,如果要求特定格式文件,可以对file.getName()进行操作并比较。