java.net.URL read stream to byte[]

后端 未结 8 461
失恋的感觉
失恋的感觉 2020-11-29 03:11

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 ent

8条回答
  •  萌比男神i
    2020-11-29 04:03

    Just extending Barnards's answer with commons-io. Separate answer because I can not format code in comments.

    InputStream is = null;
    try {
      is = url.openStream ();
      byte[] imageBytes = IOUtils.toByteArray(is);
    }
    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(); }
    }
    

    http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toByteArray(java.io.InputStream)

提交回复
热议问题