我有需要从 FTP 服务器读取的文件列表。
我有一个方法 readFile(String path, FTPClient client)
可以读取并打印文件。
public byte[] readFile(String path,FTPClient client){
InputStream inStream = null;
ByteArrayOutputStream os = null;
byte[] finalBytes = new byte[0];
int reply;
int len;
byte[] buffer = new byte[1024];
try{
os = new ByteArrayOutputStream();
inStream = client.retrieveFileStream(path);
reply = client.getReplyCode();
log.warn("In getFTPfilebytes() :: Reply code -"+reply);
while ((len = inStream.read(buffer)) != -1) {
// write bytes from the buffer into output stream
os.write(buffer, 0, len);
}
finalBytes = os.toByteArray();
if(inStream == null){
throw new Exception("File not found");
}
inStream.close();
}catch(Exception e){
}finally{
try{ inStream.close();} catch(Exception e){}
}
return finalBytes;
}
我在包含文件路径字符串的列表循环中调用上述方法。
问题 - 在循环中只有第一个文件被正确读取。之后,它不会读取文件并引发异常。 inStream
为第二次迭代/第二个文件提供 NULL。此外,在 retrieveFileStream
之后迭代第一个文件回复代码时,“125(数据连接已打开;传输开始。)”
在第二次迭代中,它给出“200(请求的操作已成功完成。)”
我无法理解这里出了什么问题。
没有正确关闭 inputstream
连接吗?
最佳答案
您必须调用FTPClient.completePendingCommand
并关闭输入流,如 FTPClient.retrieveFileStream
的文档说:
<小时/>Returns an InputStream from which a named file from the server can be read. If the current file type is ASCII, the returned InputStream will convert line separators in the file to the local representation. You must close the InputStream when you finish reading from it. The InputStream itself will take care of closing the parent data connection socket upon being closed.
To finalize the file transfer you must call
completePendingCommand
and check its return value to verify success. If this is not done, subsequent commands may behave unexpectedly.
inStream = client.retrieveFileStream(path);
try {
while ((len = inStream.read(buffer)) != -1) {
// write bytes from the buffer into output stream
os.write(buffer, 0, len);
}
finalBytes = os.toByteArray();
} finally {
inStream.close()
if (!client.completePendingCommand()) {
// error
}
}
<小时/>
顺便说一句,有更好的方法从 InputStream
复制到 OutputStream
:
Easy way to write contents of a Java InputStream to an OutputStream
关于java - 使用 Apache Commons Net FTPClient 从 FTP 服务器循环读取多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58167086/