gpt4 book ai didi

java.net.URL 读取流到字节 []

转载 作者:IT老高 更新时间:2023-10-28 20:43:17 26 4
gpt4 key购买 nike

我正在尝试从 URL 读取图像(使用 Java 包java.net.URL) 到一个字节[]。 “一切”工作正常,除了内容没有完全从流中读取(图像已损坏,它不包含所有图像数据)......字节数组被保存在数据库(BLOB)中.我真的不知道正确的方法是什么,也许你可以给我一个提示。 :)

这是我的第一种方法(代码格式化,删除了不必要的信息......):

URL u = new URL("http://localhost:8080/images/anImage.jpg");
int contentLength = u.openConnection().getContentLength();
Inputstream openStream = u.openStream();
byte[] binaryData = new byte[contentLength];
openStream.read(binaryData);
openStream.close();

我的第二种方法是这个(你会看到 contentlength 正在以另一种方式获取):

URL u = new URL(content);
openStream = u.openStream();
int contentLength = openStream.available();
byte[] binaryData = new byte[contentLength];
openStream.read(binaryData);
openStream.close();

这两个代码都导致图像损坏...我已经阅读了这篇文章 from Stack Overflow .

最佳答案

无法保证您提供的内容长度实际上是正确的。尝试类似以下的方法:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;

while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
}
catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
// Perform any other exception handling that's appropriate.
}
finally {
if (is != null) { is.close(); }
}

然后您将在 baos 中获得图像数据,您可以通过调用 baos.toByteArray() 从中获取字节数组。

此代码未经测试(我只是将其写在答案框中),但它与我认为您所追求的相当接近。

关于java.net.URL 读取流到字节 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2295221/

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