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:by.logscanner.LogScanner.java

private byte[] readGateway(File file) throws FileNotFoundException, IOException {
    return FileUtils.readFileToByteArray(file);
}

From source file:de.topobyte.largescalefileio.TestClosingFileOutputStream.java

@Test
@SuppressWarnings("resource")
public void testOpenTruncatesFile() throws IOException {
    File file = File.createTempFile("closing-fos", ".dat");
    allFiles.add(file);/*from ww  w  . j  a va 2  s.c  o  m*/

    ByteArrayGenerator generator = new ByteArrayGenerator();
    writeSomeData(file, generator);

    SimpleClosingFileOutputStreamPool factory = new SimpleClosingFileOutputStreamPool();
    new ClosingFileOutputStream(factory, file, 0);

    byte[] read = FileUtils.readFileToByteArray(file);
    Assert.assertEquals(0, read.length);
}

From source file:com.chiorichan.http.UploadedFile.java

public String getMD5() throws IOException {
    if (isInMemory() || file == null)
        return SecureFunc.md5(cachedFileUpload.content().array());
    else/*from  ww w .j a  v  a  2  s. c  o m*/
        return SecureFunc.md5(FileUtils.readFileToByteArray(file));
}

From source file:model.PayloadSegment.java

/**
 * This constructor is for spare algorithms with low capacity.
 * /* www  .  j a v a 2 s.  c  om*/
 * @param payload
 */
public PayloadSegment(File payload) {
    String payloadChecksum = "";
    try {
        this.payload = FileUtils.readFileToByteArray(payload);
        payloadChecksum += FileUtils.checksumCRC32(payload);
    } catch (IOException e) {
    }
    properties.put("payloadName", payload.getName());
    properties.put("payloadChecksum", payloadChecksum);
}

From source file:cn.com.report.HtmlServlet2.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    InputStream is = HtmlServlet2.class.getResourceAsStream("Blank_A4.jrxml");
    resp.setContentType("application/pdf");

    OutputStream out = resp.getOutputStream();
    JasperPdfExporterBuilder pdfExporter = export.pdfExporter(out);
    try {/*  w w w  . j  ava2 s .c  o  m*/
        JasperReportBuilder report = report();

        report.setTemplate(Templates.reportTemplate).setTemplateDesign(is).setParameters(createParameters())
                /*.columns(
                   col.column("Item",       "item",      type.stringType()),
                   col.column("?",   "quantity",  type.integerType()),
                   col.column("Unit price", "unitprice", type.integerType()))*/
                //           .title(Templates.createTitleComponent("TestDRByDiyDesigner"))
                .setDataSource(createDataSource()).show(false);
        File tempFile = File.createTempFile("xjjjxxxxxxxxx", ".pdf");
        report.toPdf(new FileOutputStream(tempFile));
        out.write(FileUtils.readFileToByteArray(tempFile));
        System.out.println("%%%%%%%%%%" + tempFile.getCanonicalPath());
        //         report.toPdf(pdfExporter);//?pdf?  
    } catch (DRException e) {
        e.printStackTrace();
    }
    out.close();
}

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

@Test(groups = { "unit" })
public void testEmpty() throws IOException {
    final File tempFile = File.createTempFile("temp", "");

    ZipFileCollection collection;/* ww  w.  ja  v  a  2  s.  com*/
    File[] files;

    // Java seems to choke the empty zip file!
    /*
     * copyResourceToFile(tempFile, "empty.zip"); collection = new ZipFileCollection(tempFile);
     * 
     * files = collection.getFiles(); assert files.length == 0; assert collection.deleteAll();
     */

    this.copyResourceToFile(tempFile, "empty-file.zip");
    collection = new ZipFileCollection(tempFile);
    files = collection.getFilesArray();
    assert files.length == 1;
    assert files[0].exists();
    assert FileUtils.readFileToByteArray(files[0]).length == 0;
    assert collection.deleteAll();
    assert !files[0].exists();

    assert collection.getZipEntryNames().length == 1;
    assert collection.getZipEntryNames()[0].equals("empty");

    this.copyResourceToFile(tempFile, "hello.zip");
    collection = new ZipFileCollection(tempFile);
    files = collection.getFilesArray();
    assert files.length == 2 : "Length of files is " + files.length;
    assert files[0].exists() && files[1].exists();
    this.assertHelloWorldContents(files[0]);
    this.assertHelloWorldContents(files[1]);
    assert collection.deleteAll();
    assert !files[0].exists() && !files[1].exists();

    assert collection.getZipEntryNames().length == 2;
    assert collection.getZipEntryNames()[0].startsWith("hello");
    assert collection.getZipEntryNames()[1].startsWith("hello");

}

From source file:com.cws.esolutions.agent.processors.impl.FileManagerProcessorImplTest.java

@Test
public final void testDeployFile() {
    try {/*from   w  w w .  j  a v a2s .c  om*/
        FileManagerRequest request = new FileManagerRequest();
        request.setRequestFile("C:\\var\\mydir\\somedir\\myfile");
        request.setFileData(FileUtils.readFileToByteArray(FileUtils.getFile("C:\\Temp\\cust.sql")));

        FileManagerResponse response = processor.deployFile(request);

        Assert.assertEquals(AgentStatus.SUCCESS, response.getRequestStatus());
    } catch (FileManagerException fmx) {
        Assert.fail(fmx.getMessage());
    } catch (IOException iox) {
        Assert.fail(iox.getMessage());
    }
}

From source file:com.playonlinux.core.utils.archive.TarTest.java

private void testUncompress(String fileName) throws IOException {
    final File inputFile = new File(inputUrl.getPath(), fileName);
    final File temporaryDirectory = Files.createTempDir();

    temporaryDirectory.deleteOnExit();/*from   w  w  w .j a  v  a2 s  .c om*/

    final List<File> extractedFiles = new Extractor().uncompress(inputFile, temporaryDirectory);

    assertTrue(new File(temporaryDirectory, "directory1").isDirectory());
    final File file1 = new File(temporaryDirectory, "file1.txt");
    final File file2 = new File(temporaryDirectory, "file2.txt");
    final File file0 = new File(new File(temporaryDirectory, "directory1"), "file0.txt");

    assertTrue(file1.exists());
    assertTrue(file2.exists());
    assertTrue(file0.exists());

    assertEquals("file1content", new String(FileUtils.readFileToByteArray(file1)));
    assertEquals("file2content", new String(FileUtils.readFileToByteArray(file2)));
    assertEquals("file0content", new String(FileUtils.readFileToByteArray(file0)));

    assertEquals(5, extractedFiles.size());
}

From source file:com.pronoiahealth.olhie.server.rest.TVServiceImpl.java

/**
 * @see com.pronoiahealth.olhie.server.rest.TVService#getVideo(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.String,
 *      javax.servlet.ServletContext)//from w  w w  .j  a  va  2  s .c  om
 */
@Override
@GET
@Path("/tv/{uniqueNumb}/{programRef}")
// @Produces({"application/pdf", "application/octet-stream", "text/html"})
@Produces({ "application/octet-stream" })
@SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR, SecurityRoleEnum.REGISTERED,
        SecurityRoleEnum.ANONYMOUS })
public InputStream getVideo(@Context HttpServletRequest request, @Context HttpServletResponse response,
        @PathParam("programRef") String programRef, @Context ServletContext context)
        throws ServletException, IOException, FileDownloadException {
    DataInputStream in = null;
    try {
        // Get the file contents
        File programFile = findFile(programRef);
        if (programFile == null) {
            throw new FileDownloadException(String.format("Could not find file for id %s", programRef));
        }

        String fileName = programRef.substring(programRef.lastIndexOf("|"));
        String mimetype = context.getMimeType(fileName);
        // Base64 unencode
        byte[] fileBytes = FileUtils.readFileToByteArray(programFile);

        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");

        // No image caching
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // response.setContentLength(fileBytes.length);
        // response.setHeader("Content-Disposition", "inline; filename="
        // + fileName);

        in = new DataInputStream(new ByteArrayInputStream(fileBytes));
        return in;
    } catch (Exception e) {
        log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);

        if (e instanceof FileDownloadException) {
            throw (FileDownloadException) e;
        } else {
            throw new FileDownloadException(e);
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.feedzai.fos.impl.weka.utils.Cloner.java

/**
 * Creates a clonner by reading a serialized object from file.
 *
 * @param descriptor A {@link com.feedzai.fos.api.ModelDescriptor} with the information about the classifier.
 * @throws IOException when there were problems reading the file
 *///from   w ww  .  j a  v a  2 s.  com
public Cloner(ModelDescriptor descriptor) throws IOException {
    checkNotNull(descriptor.getModelFilePath(), "Source file cannot be null");

    File file = new File(descriptor.getModelFilePath());

    checkArgument(file.exists(), "Source file '" + file.getAbsolutePath() + "' must exist");

    switch (descriptor.getFormat()) {
    case BINARY:
        this.serializedObject = FileUtils.readFileToByteArray(file);
        break;
    case PMML:
        try {
            this.serializedObject = SerializationUtils.serialize(PMMLConsumers.consume(file));
        } catch (FOSException e) {
            throw new RuntimeException("Failed to consume PMML file.", e);
        }
        break;
    }
}