Here you can find the source of getResourceAsBytes(ClassLoader classLoader, String resourcePath)
Parameter | Description |
---|---|
classLoader | e.g. obj.getClass().getClassLoader(); |
resourcePath | e.g. "com/wilutions/officeaddin/RibbonManifest.xml" |
Parameter | Description |
---|---|
IOException | an exception |
public static byte[] getResourceAsBytes(ClassLoader classLoader, String resourcePath) throws IOException
//package com.java2s; /*//from w w w. j a v a 2 s . co m Copyright (c) 2014 Wolfgang Imig This file is part of the library "Java Add-in for Microsoft Office". This file must be used according to the terms of MIT License, http://opensource.org/licenses/MIT */ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class Main { /** * Return resource as byte array. * * @param classLoader * e.g. obj.getClass().getClassLoader(); * @param resourcePath * e.g. "com/wilutions/officeaddin/RibbonManifest.xml" * @return Resource content. * @throws IOException */ public static byte[] getResourceAsBytes(ClassLoader classLoader, String resourcePath) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = null; try { is = classLoader.getResourceAsStream(resourcePath); if (is == null) throw new IOException("Resource " + resourcePath + " not found."); byte[] buf = new byte[1000]; int len = 0; while ((len = is.read(buf)) != -1) { bos.write(buf, 0, len); } } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } return bos.toByteArray(); } /** * Return resource as byte array. * @param forClass Class object that defines the package of the resourceName. * @param resourceName Name of the resource relative to the package of forClass. * @return Resource object. * @throws IOException */ public static byte[] getResourceAsBytes(Class<?> forClass, String resourceName) throws IOException { ClassLoader classLoader = forClass.getClassLoader(); String resourcePath = forClass.getPackage().getName().replace('.', '/') + "/" + resourceName; return getResourceAsBytes(classLoader, resourcePath); } }