Java Resource Load getResourceAsBytes(Class cl, String resname)

Here you can find the source of getResourceAsBytes(Class cl, String resname)

Description

get Resource As Bytes

License

Apache License

Declaration

public static byte[] getResourceAsBytes(Class cl, String resname) throws IOException 

Method Source Code


//package com.java2s;
/*/* w w w .j  ava2 s.c o  m*/
 * Copyright 2005-2006
 * Wolfgang S. Kechel, data2c GmbH (www.data2c.com)
 * 
 * Author: Wolfgang S. Kechel - wolfgang.kechel@data2c.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.InputStream;
import java.io.DataInputStream;

import java.io.IOException;

public class Main {
    public static byte[] getResourceAsBytes(Class cl, String resname) throws IOException {
        DataInputStream is = new DataInputStream(getResourceAsStream(cl, resname));
        byte[] buf = new byte[512];
        int bytesread = 0;
        byte[] result = new byte[bytesread];
        int i = 0;
        int n = 0;

        while ((n = is.read(buf, 0, buf.length)) > 0) {
            byte[] newres = new byte[n + bytesread];
            for (i = 0; i < bytesread; ++i) {
                newres[i] = result[i];
            }
            for (i = 0; i < n; ++i, ++bytesread) {
                newres[bytesread] = buf[i];
            }
            result = newres;
            System.gc();
        }
        is.close();
        return result;
    }

    public static InputStream getResourceAsStream(Class cl, String resname) {
        //System.err.println("getResourceAsStream("+cl+", "+resname);
        //InputStream s = cl.getResourceAsStream(resname);
        //System.err.println("\t-->"+s);
        //return s;
        return cl.getResourceAsStream(resname);
    }
}

Related

  1. getResource(String uri)
  2. getResourceAbsolutePath(String pluginId, String... path)
  3. getResourceAsBufferedReader(Class clazz, String resourceName)
  4. getResourceAsByteArray(Object context, String resourceName)
  5. getResourceAsByteArray(String url)
  6. getResourceAsBytes(Class testClass, String resourceName)
  7. getResourceAsBytes(ClassLoader classLoader, String resourcePath)
  8. getResourceAsBytes(String path, ClassLoader loader)
  9. getResourceAsBytes(String url)