Example usage for org.apache.commons.io IOUtils toByteArray

List of usage examples for org.apache.commons.io IOUtils toByteArray

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils toByteArray.

Prototype

public static byte[] toByteArray(String input) throws IOException 

Source Link

Document

Get the contents of a String as a byte[] using the default character encoding of the platform.

Usage

From source file:com.formkiq.core.util.Zips.java

/**
 * Extract Zip file to Map.//from  w  w w .  ja v  a2  s.co m
 * @param bytes byte[]
 * @return {@link Map}
 * @throws IOException IOException
 */
public static Map<String, byte[]> extractZipToMap(final byte[] bytes) throws IOException {

    Map<String, byte[]> map = new HashMap<>();
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    ZipInputStream zipStream = new ZipInputStream(is);

    try {

        ZipEntry entry = null;

        while ((entry = zipStream.getNextEntry()) != null) {

            String filename = entry.getName();
            byte[] data = IOUtils.toByteArray(zipStream);
            map.put(filename, data);
        }

    } finally {

        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(zipStream);
    }

    return map;
}

From source file:com.imag.nespros.network.devices.UtilityDevice.java

public UtilityDevice(String name) {
    super(name);// w ww  . j a  v a 2 s.  co m
    this.setCpuSpeed(500);
    this.setTotalMemory(10);
    this.setDeviceType(DeviceType.UTILITY);
    this.setDeviceName(name);
    try {
        byte[] imageInByte;
        imageInByte = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("image/utility.jpg"));
        icon = new MyLayeredIcon(new ImageIcon(imageInByte).getImage());
    } catch (IOException ex) {
        Logger.getLogger(AMIDevice.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.samczsun.helios.Resources.java

public static void loadAllImages() {
    if (Thread.currentThread() != Display.getDefault().getThread()) {
        throw new IllegalArgumentException("Wrong thread");
    }/*from  w  w  w .  j a  va 2 s.  c om*/
    for (Resources resources : Resources.values()) {
        try {
            resources.data = IOUtils.toByteArray(Resources.class.getResourceAsStream(resources.filePath));
            resources.image = new Image(Display.getDefault(), resources.getData());
        } catch (IOException exception) {
            ExceptionHandler.handle(exception);
        }
    }
}

From source file:de.unisb.cs.st.javalanche.mutation.testutil.TestUtil.java

public static List<Mutation> getMutationsForClazzOnClasspath(Class<?> clazz) throws IOException {
    String fileName = clazz.getCanonicalName().replace('.', '/') + ".class";
    InputStream is = TestUtil.class.getClassLoader().getResourceAsStream(fileName);
    byte[] byteArray = IOUtils.toByteArray(is);
    return getMutations(byteArray, clazz.getCanonicalName());
}

From source file:com.t3.persistence.FileUtil.java

public static byte[] loadFile(File file) throws IOException {
    try (InputStream is = new FileInputStream(file);) {
        return IOUtils.toByteArray(is);
    }/*from  w w w. j ava 2s.  c o  m*/
}

From source file:com.floreantpos.license.FiveStarPOSLicenseGenerator.java

private static PrivateKey readPrivateKey(InputStream privateKey)
        throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(IOUtils.toByteArray(privateKey));
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PrivateKey key = keyFactory.generatePrivate(keySpec);
    return key;/*w  w  w.  j  av a2s . c  o  m*/
}

From source file:com.hviper.codec.uodecode.PeakSignalNoiseRatioTest.java

private double computePsnrPcm16(String uoResource, String referenceResource) throws Exception {
    // Read the UO file and the reference encoder's decode output into byte arrays
    byte uoFile[] = IOUtils.toByteArray(this.getClass().getResourceAsStream(uoResource));
    byte referenceWavFile[] = IOUtils.toByteArray(this.getClass().getResourceAsStream(referenceResource));

    // Decode the UO file ourselves into a byte array
    ByteArrayOutputStream decodedWavOutputStream = new ByteArrayOutputStream(referenceWavFile.length);
    UODecode.uoToPcm16Wav(uoFile, decodedWavOutputStream);
    byte decodedWavFile[] = decodedWavOutputStream.toByteArray();

    // Find the start of the sample data; this will be after a 'data' header and four bytes of
    // content length.
    int dataStart = -1;
    for (int i = 0; i < decodedWavFile.length - 4; ++i) {
        if ((decodedWavFile[i] == 'd') && (decodedWavFile[i + 1] == 'a') && (decodedWavFile[i + 2] == 't')
                && (decodedWavFile[i + 3] == 'a')) {
            dataStart = i + 8; // 8 = length of header + chunk length
            break;
        }//ww  w  .ja  v a  2  s.c  om
    }
    assertFalse("No 'data' header in decoded output", dataStart < 0);

    // Headers must be equal. Compare as hex strings for better assert failures here.
    String refHeaders = DatatypeConverter.printHexBinary(Arrays.copyOfRange(referenceWavFile, 0, dataStart));
    String ourHeaders = DatatypeConverter.printHexBinary(Arrays.copyOfRange(decodedWavFile, 0, dataStart));
    assertEquals("WAV headers do not match", refHeaders, ourHeaders);
    assertEquals("File lengths do not match", referenceWavFile.length, decodedWavFile.length);

    // Compute total squared error
    int cursor = dataStart;
    long totalSqError = 0;
    int sampleCount = 0;
    int worstSoFar = 0;
    for (; (cursor + 1) < referenceWavFile.length; cursor += 2) {
        short refSample = (short) ((referenceWavFile[cursor] & 0xff)
                | ((referenceWavFile[cursor + 1] & 0xff) << 8));
        short ourSample = (short) ((decodedWavFile[cursor] & 0xff)
                | ((decodedWavFile[cursor + 1] & 0xff) << 8));
        int absDiff = Math.abs(ourSample - refSample);

        long sqError = ((long) absDiff) * ((long) absDiff);
        totalSqError += sqError;
        ++sampleCount;
    }
    assertNotEquals("No samples read!", 0, sampleCount);

    // Compute the PSNR in decibels; higher the better
    double psnr;
    if (totalSqError > 0) {
        double sqrtMeanSquaredError = Math.sqrt((double) (totalSqError) / (double) (sampleCount));
        double maxValue = 65535.0;
        psnr = 20.0 * Math.log10(maxValue / sqrtMeanSquaredError);
    } else {
        // Identical! Pick a large PSNR result
        psnr = 1000.0;
    }

    return psnr;
}

From source file:de.brazzy.nikki.model.ImageWriter.java

private static byte[] readEmptyExif() {
    try {/*w w w .j ava2  s  .  com*/
        return IOUtils.toByteArray(ImageWriter.class.getResourceAsStream("empty_exif.bin"));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hurence.logisland.util.file.FileUtil.java

/**
 * load file from resources as a bytes array or return null if an error occurs
 *//*from  w  w w .  j  a v  a2s.  co  m*/
public static byte[] loadFileContentAsBytes(String path) {
    try {
        final InputStream is = FileUtil.class.getClassLoader().getResourceAsStream(path);
        assert is != null;
        byte[] encoded = IOUtils.toByteArray(is);
        is.close();
        return encoded;
    } catch (Exception e) {
        logger.error(String.format("Could not load file %s and convert it to a bytes array", path), e);
        return null;
    }
}

From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsTestUtil.java

public static byte[] getBytes(InputStream inputStream) throws IOException {
    byte[] fileBytes = null;
    try {//  ww w .  j a  v a 2s .com
        fileBytes = IOUtils.toByteArray(inputStream);
    } finally {
        inputStream.close();
    }
    return fileBytes;
}