Example usage for org.apache.commons.io FileUtils readFileToByteArray

List of usage examples for org.apache.commons.io FileUtils readFileToByteArray

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readFileToByteArray.

Prototype

public static byte[] readFileToByteArray(File file) throws IOException 

Source Link

Document

Reads the contents of a file into a byte array.

Usage

From source file:com.streamsets.pipeline.lib.generator.protobuf.TestProtobufDataGenerator.java

@Test
public void writeWithOneOfAndMap() throws Exception {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    byte[] expected = FileUtils
            .readFileToByteArray(new File(Resources.getResource("TestProtobuf3.ser").getPath()));
    DataGenerator dataGenerator = getDataGenerator(bOut, "TestRecordProtobuf3.desc", "TestRecord");

    Record record = getContext().createRecord("");
    Map<String, Field> rootField = new HashMap<>();
    rootField.put("first_name", Field.create("Adam"));
    rootField.put("full_name", Field.create(Field.Type.STRING, null));
    rootField.put("samples", Field.create(ImmutableList.of(Field.create(1), Field.create(2))));
    Map<String, Field> entries = ImmutableMap.of("hello", Field.create("world"), "bye", Field.create("earth"));
    rootField.put("test_map", Field.create(entries));
    record.set(Field.create(rootField));

    dataGenerator.write(record);//from   ww  w.jav  a2s . c  om
    dataGenerator.flush();
    dataGenerator.close();

    assertArrayEquals(expected, bOut.toByteArray());
}

From source file:edu.umn.msi.tropix.common.test.FileDisposableResourceFactoryTest.java

@Test(groups = "unit", timeOut = 1000)
public void fromByte() throws IOException {
    final byte[] bytes = new byte[10];
    RANDOM.nextBytes(bytes);//ww  w . jav a 2 s .  c o  m

    final DisposableResource resource = FileDisposableResourceFactory.getByteFunciton().apply(bytes);
    final File file = resource.getFile();
    assert file.exists();
    final byte[] fileBytes = FileUtils.readFileToByteArray(file);
    assert Arrays.equals(bytes, fileBytes);
    resource.dispose();
    assert !file.exists();
}

From source file:com.github.dactiv.fear.service.web.SystemCommonController.java

/**
 * ? freemarker ?//from  w  ww. j  ava  2s . c  o m
 *
 * @param name ???
 *
 * @return ?
 */
@RequestMapping("get-ftl-template")
public ResponseEntity<byte[]> getFtlTemplate(@RequestParam String name, HttpServletRequest request)
        throws IOException {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_PLAIN);

    String path = request.getSession().getServletContext().getRealPath("") + ftlTemplatePath + name + ".ftl";
    byte[] bytes = FileUtils.readFileToByteArray(new File(path));

    return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}

From source file:com.acciente.commons.loader.JavaCompiledClassDef.java

private void loadCompiledClassFile() throws ClassNotFoundException {
    try {/*from  w ww  .ja v  a 2 s.  com*/
        // checkpoint the compiled file's modified date before the compile
        long iLastModifiedTimeAtLastLoad = _oCompiledFile.lastModified();

        _ayClassByteCode = FileUtils.readFileToByteArray(_oCompiledFile);

        _iLastModifiedTimeAtLastLoad = iLastModifiedTimeAtLastLoad;

        readReferencedClasses(_ayClassByteCode, _oCompiledFile.getName());
    } catch (IOException e) {
        throw new ClassNotFoundException("Error loading class definition", e);
    }
}

From source file:net.darkmist.alib.io.Slurp.java

/**
 * @deprecated Use {@link org.apache.commons.io.FileUtils#readFileToByteArray(java.io.File)} instead
 *///www. ja v  a2 s  .c o  m
@Deprecated
public static byte[] slurp(File file) throws IOException {
    return FileUtils.readFileToByteArray(file);
}

From source file:com.bbva.kltt.apirest.core.web.Utilities.java

/**
 * Read the file content/*from w w w. j  a  v  a 2  s.  c  o m*/
 * @param filePath with the file path
 * @return the file content as byte array
 * @throws APIRestGeneratorException with an occurred exception
 */
public static byte[] readFileContent(final String filePath) throws APIRestGeneratorException {
    Path path = null;

    if (filePath.toLowerCase().startsWith(ConstantsInput.SO_PATH_STRING_PREFIX)) {
        path = Paths.get(URI.create(filePath));
    } else {
        path = Paths.get(filePath, new String[0]);
    }

    byte[] fileContent = null;

    if (Files.exists(path, new LinkOption[0])) {
        try {
            fileContent = FileUtils.readFileToByteArray(path.toFile());
        } catch (IOException ioException) {
            final String errorString = "IOException when reading the file '" + filePath + "': " + ioException;

            Utilities.LOGGER.error(errorString, ioException);
            throw new APIRestGeneratorException(errorString, ioException);
        }
    }

    return fileContent;
}

From source file:br.ufpr.gres.core.classpath.Resources.java

private List<ClassDetails> getClasses(final File file, String filter)
        throws IOException, ClassNotFoundException {
    final List<ClassDetails> classNames = new LinkedList<>();

    if (file.exists()) {
        for (final File f : file.listFiles()) {
            if (f.isDirectory()) {
                classNames.addAll(getClasses(f, filter));
            } else if (f.getName().endsWith(filter)) {
                final ClassContext context = new ClassContext();
                final ClassReader first = new ClassReader(FileUtils.readFileToByteArray(f));
                final NullVisitor nv = new NullVisitor();
                final RegisterInformationsClassVisitor mca = new RegisterInformationsClassVisitor(context, nv);

                first.accept(mca, ClassReader.EXPAND_FRAMES);

                classNames.add(new ClassDetails(context.getClassInfo(), f, this.root));
            }/*from  w ww. j  av a 2 s  . co  m*/
        }
    }

    return classNames;
}

From source file:com.athena.chameleon.web.system.controller.SystemController.java

/**
 *   //from  ww w . ja va 2 s . c  o m
 * 
 * @param model
 * @param modelMap
 * @param session
 * @return
 * @throws Exception
 */
@RequestMapping("/codeForm.do")
public String showCode(Model model, ModelMap modelMap, HttpSession session) throws Exception {

    String loginFlag = String.valueOf(session.getAttribute("loginFlag"));
    if (loginFlag == null || !loginFlag.equals("Y"))
        return "redirect:/login/showLogin.do";

    File filteringResource = new File(PropertyUtil.class.getResource("/filtering.properties").getFile());
    CharsetDetector detector = new CharsetDetector();
    detector.setText(FileUtils.readFileToByteArray(filteringResource));
    String filteringCode = FileUtils.readFileToString(filteringResource, detector.detect().getName());

    File contextResource = new File(PropertyUtil.class.getResource("/config/context.properties").getFile());
    detector.setText(FileUtils.readFileToByteArray(contextResource));
    String contextCode = FileUtils.readFileToString(contextResource, detector.detect().getName());

    modelMap.addAttribute("filteringCode", filteringCode);
    modelMap.addAttribute("contextCode", contextCode);

    return "/main/system/codeForm";
}

From source file:model.PayloadSegment.java

/**
 * A payload segment consists of: START_SEQ, restoration metadata,
 * END_HEADER_SEQ, payload bytes, END_SEQ.
 * /*from  w w w.  j av  a 2 s  .  c o m*/
 * The restoration metadata is saved in a {@link Properties} class, and
 * keeps the name of carrier and payload, as well as their checksums and the
 * name of the algorithm used to encapsulate.
 * 
 * @param carrier
 * @param payload
 * @param algorithm
 */
public PayloadSegment(File carrier, File payload, AbstractAlgorithm algorithm) {
    String payloadChecksum = "";
    String carrierChecksum = "";
    try {
        this.payload = FileUtils.readFileToByteArray(payload);
        payloadChecksum += FileUtils.checksumCRC32(payload);
        carrierChecksum += FileUtils.checksumCRC32(carrier);
    } catch (IOException e) {
    }
    properties.put("carrierName", carrier.getName());
    properties.put("carrierChecksum", carrierChecksum);
    properties.put("payloadName", payload.getName());
    properties.put("payloadChecksum", payloadChecksum);
    properties.put("algorithm", algorithm.getClass().getName());
    properties.put("carrierPath", "" + carrier.getAbsolutePath());
    properties.put("payloadPath", "" + payload.getAbsolutePath());
}

From source file:de.undercouch.gradle.tasks.download.DownloadExtensionTest.java

/**
 * Tests if a single file can be downloaded
 * @throws Exception if anything goes wrong
 *//*from   w  w w. j av  a 2s  .c  om*/
@Test
public void downloadSingleFile() throws Exception {
    Download t = makeProjectAndTask();

    String src = makeSrc(TEST_FILE_NAME);
    File dst = folder.newFile();

    doDownload(t.getProject(), src, dst);

    byte[] dstContents = FileUtils.readFileToByteArray(dst);
    assertArrayEquals(contents, dstContents);
}