gpt4 book ai didi

java - 使用 Apache Commons Net FTPClient 从 FTP 服务器循环读取多个文件

转载 作者:太空宇宙 更新时间:2023-11-04 09:22:16 26 4
gpt4 key购买 nike

我有需要从 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 servercan be read. If the current file type is ASCII, the returnedInputStream will convert line separators in the file tothe local representation. You must close the InputStream when youfinish reading from it. The InputStream itself will take care ofclosing the parent data connection socket upon being closed.

To finalize the file transfer you must call completePendingCommand andcheck 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/

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