java.net.URL read stream to byte[]

后端 未结 8 462
失恋的感觉
失恋的感觉 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 04:10

    Here's a clean solution:

    private byte[] downloadUrl(URL toDownload) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    
        try {
            byte[] chunk = new byte[4096];
            int bytesRead;
            InputStream stream = toDownload.openStream();
    
            while ((bytesRead = stream.read(chunk)) > 0) {
                outputStream.write(chunk, 0, bytesRead);
            }
    
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    
        return outputStream.toByteArray();
    }
    

提交回复
热议问题