gpt4 book ai didi

java - BufferedInputStream不为空,但没有数据可供读取

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

我第一次遇到这种行为。我有从 SFTP 服务器获取文件并返回它的 byte[] 表示的方法。但我无法得到正确的结果(它始终是字节[0])。
InputStream不为空,BufferedInputStream也不为空。 BufferedInputStream buf[] 包含大约 8kb 的数组(我的另一侧有小图片)。
但是

bis.available()

始终返回 0;
我错过了什么?

public static byte[] downloadFileasBytes(String remoteFilePath){
StandardFileSystemManager manager = new StandardFileSystemManager();

try {
manager.init();

// Create remote file object
FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());
try(InputStream is = remoteFile.getContent().getInputStream();){
BufferedInputStream bis = new BufferedInputStream(is);
byte[] byterepr = new byte[bis.available()];
bis.read(byterepr);

return byterepr;
}catch(Exception ex){
Logger.getLogger(SFTPUtility.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
} catch (Exception ex) {
Logger.getLogger(SFTPUtility.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
manager.close();
}

}


UPD


好吧,我以后会尽量不再犯这样的错误。
现在我通过这种方式解决了这个问题。

try(InputStream is = remoteFile.getContent().getInputStream();BufferedInputStream bis = new BufferedInputStream(is);ByteArrayOutputStream baos = new ByteArrayOutputStream()){
IOUtil.copy(bis, baos);
return baos.toByteArray();

}

最佳答案

InputStream.available() 的 javadoc 中所述(强调我的),你不应该依赖 available():

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream ...

Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.

关于java - BufferedInputStream不为空,但没有数据可供读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28500682/

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