java.net.URL read stream to byte[]

后端 未结 8 434
失恋的感觉
失恋的感觉 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:08

    Use commons-io IOUtils.toByteArray(URL):

    String url = "http://localhost:8080/images/anImage.jpg";
    byte[] fileContent = IOUtils.toByteArray(new URL(url));
    

    Maven dependency:

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
    
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
提交回复
热议问题