/** * Get the resource content as a byte array. Fail if the resource does not exist, or if we failed * to read the resource file. * * @param resource The resource to read. * @return The resource content as byte array. */ public static byte[] getResourceAsBytes(String resource) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (InputStream in = getResourceAsStream(resource)) { IOUtils.copy(in, baos); } catch (IOException e) { fail("Failed to read resource " + resource + ": " + e.getMessage()); } return baos.toByteArray(); }
/** * Copy a resource to the target directory. The resource file retains it's name. * * @param resource The resource path. * @param dir Target directory. */ public static void copyResourceTo(String resource, File dir) { if (!dir.exists()) { fail("Trying to copy resource " + resource + " to non-existing directory: " + dir); } if (dir.isFile()) { fail("Trying to copy resource " + resource + " to file: " + dir + ", directory required"); } int i = resource.lastIndexOf('/'); File file = new File(dir, resource.substring(i + 1)); try (FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream out = new BufferedOutputStream(fos); InputStream in = getResourceAsStream(resource)) { IOUtils.copy(in, out); out.flush(); fos.getFD().sync(); } catch (IOException e) { throw new UncheckedIOException(e); } }