Java Resource Get getResourceAsBytes(String resource)

Here you can find the source of getResourceAsBytes(String resource)

Description

get Resource As Bytes

License

Open Source License

Declaration

static public byte[] getResourceAsBytes(String resource) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;

import java.net.URL;

public class Main {
    static public byte[] getResourceAsBytes(String resource) throws Exception {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        URL url = cl.getResource(resource);
        InputStream is = url.openStream();
        byte[] data = getStreamContentAsBytes(is);
        is.close();/*from ww  w.  j av  a 2 s .c  o  m*/
        return data;
    }

    static public byte[] getStreamContentAsBytes(InputStream is) throws IOException {
        BufferedInputStream buffer = new BufferedInputStream(is);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] data = new byte[4912];
        int available = -1;
        while ((available = buffer.read(data)) > -1) {
            output.write(data, 0, available);
        }
        is.close();
        return output.toByteArray();
    }

    static public byte[] getStreamContentAsBytes(InputStream is, int maxRead) throws IOException {
        BufferedInputStream buffer = new BufferedInputStream(is);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] data = new byte[4912];
        int available = -1, read = 0;
        while ((available = buffer.read(data)) > -1 && read < maxRead) {
            if (maxRead - read < available)
                available = maxRead - read;
            output.write(data, 0, available);
            read += available;
        }
        return output.toByteArray();
    }
}

Related

  1. getResource(String name)
  2. getResource(String name, Class neighbor)
  3. getResource(String name, Class caller)
  4. getResource(String res)
  5. getResource(String resource, Class context)
  6. getResourceAsBytes(String resource)
  7. getResourceAsFile(Class clazz, String resource)
  8. getResourceAsFile(Class klass, String resource)
  9. getResourceAsFile(Class sourceClass, String reference)