gpt4 book ai didi

java - 如何从 org.apache.commons.net.ftp.FTPFile 转换为字符串?

转载 作者:行者123 更新时间:2023-12-02 04:29:04 25 4
gpt4 key购买 nike

我正在使用 ftpClient.listFiles() 从 FTPClient 检索文件列表;它返回一个具有正确文件名和适当数量的数组。

我正在尝试从文件中读取内容,但只有 ftpClient.retrieveFileStream(fileName) 可用于此目的。它在读取第一个文件后以某种方式中断并返回 null。

有没有办法将FTPFile直接转换为String?

    ftp.connect();
ftp.changeWorkingDirectoryToFrom();

List<String> idsList = new ArrayList<String>();

List<String> names = ftp.listFileNames();
for (String fileName : names) {
String content = fromFTPFileToString(fileName);
Matcher matcher = FILES_PATTERN.matcher(content);
String id = extractId(content);

if (matcher.find()) {
boolean duplicate = idsList.contains(id);
LOG.info("MATCHED: " + fileName);
if (!duplicate) {
ftp.moveFileFromTo(fileName);
idsList.add(id);
} else {
LOG.info("DUPLICATE: " + fileName);
duplicated++;
ftp.deleteFileOnFromFtp(fileName);
}
}
processed++;
}
ftp.disconnect();

private String fromFTPFileToString(String fileName) {
String content = "";
try {
InputStream is = ftp.readContentFromFTPFile(fileName);
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, ENCODING);
content = writer.toString();

IOUtils.closeQuietly(is);
IOUtils.closeQuietly(writer);
} catch (Exception ex) {
LOG.error(ex);
}

return content;
}

void deleteFileOnFromFtp(String fileName) {
changeWorkingDirectory(properties.getProperty(PropertiesType.FOLDER_FROM.toString()));
deleteFile(fileName);
}

InputStream readContentFromFTPFile(String fileName) {
changeWorkingDirectory(properties.getProperty(PropertiesType.FOLDER_FROM.toString()));
InputStream inputStream = null;
try {
inputStream = ftpClient.retrieveFileStream(fileName);
} catch (IOException ex) {
LOG.error("Unable to extract content from file:" + O_Q + fileName + C_Q);
}
return inputStream;
}

void moveFileFromTo(String fileName) {
String from = FORWARD_SLASH + properties.getProperty(PropertiesType.FOLDER_FROM.toString()) + FORWARD_SLASH + fileName;
String to = FORWARD_SLASH + properties.getProperty(PropertiesType.FOLDER_TO.toString()) + FORWARD_SLASH + fileName;

try {
ftpClient.rename(from, to);
} catch (IOException ex) {
LOG.error("Unable to move file file from:" + O_Q + from + C_Q + " to: " + O_Q + to + C_Q);
throw new RuntimeException(ex.getCause());
}
}

最佳答案

3个提示

1)您可以使用retrieveFile

并使用 ByteArrayOutputStream 作为第二个参数。要从中获取字符串,只需“new String(baos.toByteArray(),[您使用的字符集]);”

2) 检查 ftpClient.completePendingCommand();

如果某些命令仍待处理

3)我曾经遇到过类似的问题,设置 ftp.enterLocalPassiveMode() 有所帮助

关于java - 如何从 org.apache.commons.net.ftp.FTPFile 转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23833923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com