java.net.URL read stream to byte[]

后端 未结 8 476
失恋的感觉
失恋的感觉 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条回答
  •  悲哀的现实
    2020-11-29 03:53

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

    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.

提交回复
热议问题