我正在使用Java 11和SpringBoot。我正在尝试创建一个FTPClient来从现有的FTP服务器读取文件。使用Apache FTPClient。
问题:
InputStream is = ftp.retrieveFileStream(file.getName());
下面总是返回一个null
InputStream。
信息:
logger.info("File name: "+file.getName()+", type: "+file.getType()+", size: "+file.getSize()+".");
返回:
文件名: cam_test,输入: 1,大小: 28。
问题:
您可以看到有一个名为“cam”的文件,为什么不能将其转换为InputStream?
代码:
import org.apache.commons.net.ftp.FTPClient;
public void processFiles() {
FTPClient ftp = new FTPClient();
try {
ftp.connect(IP_ADDRESS);
int reply = ftp.getReplyCode();
logger.info("Connected to " + IP_ADDRESS + ". ReplyCode: '"+reply+"'.");
if(!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
logger.error("FTP server ('"+IP_ADDRESS+"') refused connection.");
} else {
// transfer files
ftp.login(USERNAME, PASSWORD);
FTPFile[] files = ftp.listFiles(BASE_DIR);
logger.info("Connected to " + IP_ADDRESS + ". Got '"+files.length+"' files from working directory: "+ftp.printWorkingDirectory()+BASE_DIR+".");
for (FTPFile file : files) {
logger.info("File name: '"+file.getName()+"', type: '"+file.getType()+"', size: '"+file.getSize()+"', directory: '"+file.isDirectory()+"', file: '"+file.isFile()+"'.");
if (file.isFile() && 0 == file.getType()) {
InputStream is = ftp.retrieveFileStream(file.getName()); // <--- is always null
processFile(file, is);
if (is != null) {
is.close();
}
boolean completePendingCommand = ftp.completePendingCommand();
logger.info("completePendingCommand: "+completePendingCommand);
}
}
}
} catch(IOException e) {
logger.error(e.getMessage(), e);
} finally {
if(ftp.isConnected()) {
try {
ftp.disconnect();
} catch(IOException ioe) {
// do nothing
}
}
}
}
发布于 2022-02-18 12:42:27
必须在每个命令之后添加completePendingCommand
。
在下面的代码中,completePendingCommand被注释掉了。
for (FTPFile file : files) {
System.out.println(
"File name: " + file.getName() + ", type: " + file.getType() + ", size: " + file.getSize() + ".");
InputStream is = ftp.retrieveFileStream(file.getName());
System.out.println(is == null);
// ftp.completePendingCommand();
}
结果是:
连接到ftp.dlptest.com。220 文件名: actorstoday.txt,类型: 0,大小: 0。错误 文件名: actorstomorrow.txt,类型: 0,大小: 0。真的
正如您所看到的,第二个请求是返回一个空InputStream。
改为:
for (FTPFile file : files) {
System.out.println(
"File name: " + file.getName() + ", type: " + file.getType() + ", size: " + file.getSize() + ".");
InputStream is = ftp.retrieveFileStream(file.getName());
System.out.println(is == null);
ftp.completePendingCommand();
}
结果是:
连接到ftp.dlptest.com。220 文件名: actorstoday.txt,类型: 0,大小: 0。错误 文件名: actorstomorrow.txt,类型: 0,大小: 0。错误
在for循环的每次迭代中,您必须调用completePendingCommand
。
https://stackoverflow.com/questions/71172909
复制相似问题