我正在使用org.apache.commons.net.ftp.FTPClient并且看到的行为很好......令人费解。
下面的方法打算通过FTP文件列表,读取它们然后对内容做一些事情。这一切都奏效了。什么不是(真的)工作是FTPClient对象执行以下操作...
1) Properly retrieves and stores the FIRST file in the list
2) List item evaluates to NULL for x number of successive iterations of the loop (x varies on successive attempts
3) manages to retrieve exactly 1 more file in the list
4) reports that it is null for exactly 1 more file in the list
5) hangs indefinitely, reporting no further activity.
public static String mergeXMLFiles(List<FTPFile> files, String rootElementNodeName, FTPClient ftp){
String ret = null;
String fileAsString = null;
//InputStream inStream;
int c;
if(files == null || rootElementNodeName == null)
return null;
try {
System.out.println("GETTING " + files.size() + " files");
for (FTPFile file : files) {
fileAsString = "";
InputStream inStream = ftp.retrieveFileStream(file.getName());
if(inStream == null){
System.out.println("FtpUtil.mergeXMLFiles() couldn't initialize inStream for file:" + file.getName());
continue;//THIS IS THE PART THAT I SEE FOR files [1 - arbitrary number (usually around 20)] and then 1 more time for [x + 2] after [x + 1] passes successfully.
}
while((c = inStream.read()) != -1){
fileAsString += Character.valueOf((char)c);
}
inStream.close();
System.out.println("FILE:" + file.getName() + "\n" + fileAsString);
}
} catch (Exception e) {
System.out.println("FtpUtil.mergeXMLFiles() failed:" + e);
}
return ret;
}
有没有人见过这样的东西?我是FTPClient的新手,我做错了吗?
答案 0 :(得分:14)
根据FTPClient.retrieveFileStream()
的API,当无法打开数据连接时,该方法会返回null
,在这种情况下,您应该检查回复代码(例如getReplyCode()
,{{3 }},getReplyString()
)看看它失败的原因。此外,您可以通过调用getReplyStrings()
并验证传输确实成功来完成文件传输。
答案 1 :(得分:2)
当我在“检索”命令后添加时,它可以正常工作:
int response = client.getReply();
if (response != FTPReply.CLOSING_DATA_CONNECTION){
//TODO
}