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

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

问题描述

我试图将URL中的图像(使用java包
java.net.URL )读取到byte []。 Everything工作正常,除了内容不是从流中被读取(图像损坏,它不包含所有图像数据)...字节数组被保存在数据库(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 isnt being enterely read from the stream (the image is corrupt, it doesnt contain all the image data)... The byte array is being persisted in a database (BLOB). I really dont know what the correct approach is, maybe you can give me a tip :)

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

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

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();

这两个代码都会导致图片损坏...
我已经阅读过这篇文章从stackoverflow a>

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

推荐答案

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

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读取流到byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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