java.net.URL 读取流到字节[] [英] java.net.URL read stream to byte[]

查看:21
本文介绍了java.net.URL 读取流到字节[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to read an image from an URL (with the Java package java.net.URL) to a byte[]. "Everything" works fine, except that the content isn't being entirely read from the stream (the image is corrupt, it doesn't contain all the image data)... The byte array is being persisted in a database (BLOB). I really don't know what the correct approach is, maybe you can give me a tip. :)

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

This is my first approach (code formatted, removed unnecessary information...):

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 正在以另一种方式获取):

My second approach was this one (as you'll see the contentlength is being fetched another way):

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

这两个代码都会导致图像损坏...我已经读过这篇文章 来自堆栈溢出.

Both of the code result in a corrupted image... I already read this post from Stack Overflow.

推荐答案

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

There's no guarantee that the content length you're provided is actually correct. Try something akin to the following:

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() 从中获取一个字节数组.

You'll then have the image data in baos, from which you can get a byte array by calling baos.toByteArray().

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

This code is untested (I just wrote it in the answer box), but it's a reasonably close approximation to what I think you're after.

这篇关于java.net.URL 读取流到字节[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆