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.huawei.ais.demo.TokenDemo.java

/**
 * ?Base64???Token???//from ww  w .  j  a  v  a 2  s. c om
 * @param token token?
 * @param formFile 
 * @throws IOException
 */
public static void requestOcrVehicleLicenseBase64(String token, String formFile) {

    // 1.????
    String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/vehicle-license";
    Header[] headers = new Header[] { new BasicHeader("X-Auth-Token", token),
            new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) };
    try {
        byte[] fileData = FileUtils.readFileToByteArray(new File(formFile));
        String fileBase64Str = Base64.encodeBase64String(fileData);
        JSONObject json = new JSONObject();
        json.put("image", fileBase64Str);
        StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");

        // 2.???, POST??
        HttpResponse response = HttpClientUtils.post(url, headers, stringEntity);
        System.out.println(response);
        String content = IOUtils.toString(response.getEntity().getContent());
        System.out.println(content);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:de.unisaarland.swan.rest.services.v1.ProjectFacadeREST.java

/**
 * This method returns a zip archive containing all Users annotations project
 * related. For each document and user pair will be a single .xml file
 * created in the de.unisaarland.disacnno.export.model format.
 * //from www . ja v  a 2  s .com
 * @param projId
 * @return 
 */
@GET
@Path("/export/{projId}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response exportProjectByProjIdAsZip(@PathParam("projId") Long projId) {

    try {
        LoginUtil.check(usersDAO.checkLogin(getSessionID(), Users.RoleType.projectmanager));

        Project proj = (Project) projectDAO.find(projId, false);

        ExportUtil exportUtil = new ExportUtil(annotationDAO, linkDAO);
        File file = exportUtil.getExportDataInXML(proj);

        return Response.ok(FileUtils.readFileToByteArray(file))
                .header("Content-Disposition", "attachment; filename=\"export_" + proj.getName() + ".zip\"")
                .build();
    } catch (SecurityException e) {
        return Response.status(Response.Status.FORBIDDEN).build();
    } catch (IOException ex) {
        Logger.getLogger(ProjectFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } catch (NoResultException e) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

}

From source file:com.music.Generator.java

public static void main1(String[] args) throws Exception {
    // testing soundbanks
    Generator generator = new Generator();
    generator.configLocation = "c:/config/music";
    generator.maxConcurrentGenerations = 5;
    generator.init();//w w w .j  ava  2  s  .  c o m
    byte[] midi = FileUtils.readFileToByteArray(new File("c:/tmp/classical.midi"));
    byte[] mp3 = generator.toMp3(midi);
    FileUtils.writeByteArrayToFile(new File("c:/tmp/aa" + System.currentTimeMillis() + ".mp3"), mp3);
}

From source file:au.org.ala.spatial.util.RecordsSmall.java

private double[] getAllDouble(String file) throws Exception {
    File f = new File(file);

    int size = (int) f.length() / 8;
    double[] all = new double[size];

    byte[] e = FileUtils.readFileToByteArray(f);

    ByteBuffer bb = ByteBuffer.wrap(e);

    for (int i = 0; i < size; i++) {
        all[i] = bb.getDouble();//ww w.ja  v a2  s  . c  o  m
    }

    return all;
}

From source file:com.turn.ttorrent.client.SharedTorrent.java

/**
 * Create a new shared torrent from the given torrent file.
 *
 * @param source The <code>.torrent</code> file to read the torrent
 * meta-info from./*w  w  w . ja v  a2 s.co m*/
 * @param parent The parent directory or location of the torrent files.
 * @throws IOException When the torrent file cannot be read or decoded.
 */
public static SharedTorrent fromFile(File source, File parent) throws IOException, NoSuchAlgorithmException {
    byte[] data = FileUtils.readFileToByteArray(source);
    return new SharedTorrent(data, parent);
}

From source file:eu.planets_project.tb.impl.services.mockups.workflow.WorkflowDroidXCDLExtractorComparator.java

/**
 * Runs droid on a given File and returns an Array of PronomIDs
 * @param f1//from  ww w. ja  va  2 s.  c o m
 * @return
 * @throws Exception
 */
private String[] runDroid(File f1) throws Exception {
    //Step1: identify using droid - returns a status and a list of IDs
    URL url = null;
    try {
        url = new URL(URL_DROID);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw e;
    }
    Service service = Service.create(url, new QName(PlanetsServices.NS, Identify.NAME));
    Identify droid = service.getPort(Identify.class);
    byte[] array = FileUtils.readFileToByteArray(f1);

    //invoke the service and extract results
    IdentifyResult identify = droid.identify(new DigitalObject.Builder(Content.byValue(array)).build(), null);
    List<URI> result = identify.getTypes();
    String status = identify.getReport().getMessage();

    if (!status.equals("Positive")) {
        throw new Exception("Service execution failed");
    }
    if (result.size() < 1) {
        throw new Exception("The specified file type is currently not supported by this workflow");
    }

    String[] strings = new String[result.size()];
    for (int i = 0; i < result.size(); i++) {
        String string = result.get(i).toASCIIString();
        //received 1..n Pronom IDs
        strings[i] = string;
    }
    return strings;
}

From source file:com.igormaznitsa.charsniffer.CharSnifferMojo.java

private boolean checkFile(@Nonnull final File file, @Nonnull final CheckConfig config) {
    try {/*from w w  w . java2  s . co  m*/
        if (getLog().isDebugEnabled()) {
            getLog().debug("Sniffing file : " + file);
        }

        final String textBody = FileUtils.readFileToString(file, config.charSet);

        final StringBuilder errorMessageBuffer = new StringBuilder();

        boolean result = checkForCodes(textBody, config, errorMessageBuffer);

        if (!result && getLog().isDebugEnabled()) {
            getLog().debug("Detected wrong chars : " + errorMessageBuffer.toString());
        }

        errorMessageBuffer.setLength(0);

        if (result) {
            result &= checkForAbc(textBody, config, errorMessageBuffer);
        }

        if (!result && getLog().isDebugEnabled()) {
            getLog().debug("Detected wrong ABC chars : " + errorMessageBuffer.toString());
        }
        errorMessageBuffer.setLength(0);

        if (result) {
            result &= checkForEOL(textBody, config);
            if (!result && getLog().isDebugEnabled()) {
                getLog().debug("Detected wrong EOL");
            }
        }

        if (result && config.validateUtf8) {
            result &= isValidUTF8(FileUtils.readFileToByteArray(file));
            if (!result && getLog().isDebugEnabled()) {
                getLog().debug("File '" + file + "' contains wrong UTF-8 byte sequence");
            }
        }

        return result;
    } catch (IOException ex) {
        getLog().error("Can't read text file : " + file, ex);
        return false;
    }
}

From source file:be.fedict.eid.idp.admin.webapp.bean.RPBean.java

@Override
@Begin(join = true)/*www. ja  va  2  s  .c o m*/
public void uploadListenerPublic(UploadEvent event) throws IOException {
    UploadItem item = event.getUploadItem();
    this.log.debug(item.getContentType());
    this.log.debug(item.getFileSize());
    this.log.debug(item.getFileName());

    byte[] attributePublicKeyBytes;
    if (null == item.getData()) {
        // meaning createTempFiles is set to true in the SeamFilter
        attributePublicKeyBytes = FileUtils.readFileToByteArray(item.getFile());
    } else {
        attributePublicKeyBytes = item.getData();
    }

    try {
        this.selectedRP.setAttributePublicKey(CryptoUtil.getPublicFromPem(attributePublicKeyBytes));
    } catch (KeyLoadException e) {
        this.log.error(e);
        this.facesMessages.addToControl("upload_secret", "Failed to load key");
    }
}

From source file:com.igormaznitsa.zxpoly.MainForm.java

private RomData loadRom(final String romPath) throws IOException {
    if (romPath != null) {
        if (romPath.contains("://")) {
            try {
                final String cached = "loaded_"
                        + Integer.toHexString(romPath.hashCode()).toUpperCase(Locale.ENGLISH) + ".rom";
                final File cacheFolder = new File(AppOptions.getInstance().getAppConfigFolder(), "cache");
                final File cachedRom = new File(cacheFolder, cached);
                RomData result = null;/*  w  w w.java 2  s.  co  m*/
                boolean load = true;
                if (cachedRom.isFile()) {
                    log.info("Load cached ROM downloaded from '" + romPath + "' : " + cachedRom);
                    result = new RomData(FileUtils.readFileToByteArray(cachedRom));
                    load = false;
                }

                if (load) {
                    log.info("Load ROM from external URL: " + romPath);
                    result = ROMLoader.getROMFrom(romPath);
                    if (cacheFolder.isDirectory() || cacheFolder.mkdirs()) {
                        FileUtils.writeByteArrayToFile(cachedRom, result.getAsArray());
                        log.info("Loaded ROM saved in cache as file : " + romPath);
                    }
                }
                return result;
            } catch (Exception ex) {
                log.log(Level.WARNING, "Can't load ROM from '" + romPath + "\'", ex);
            }
        } else {
            log.info("Load ROM from embedded resource '" + romPath + "'");
            return RomData.read(Utils.findResourceOrError("com/igormaznitsa/zxpoly/rom/" + romPath));
        }
    }

    final String testRom = "zxpolytest.rom";
    log.info("Load ROM from embedded resource '" + testRom + "'");
    return RomData.read(Utils.findResourceOrError("com/igormaznitsa/zxpoly/rom/" + testRom));
}

From source file:com.mengge.android.AndroidDriver.java

@Override
public void pushFile(String remotePath, File file) throws IOException {
    checkNotNull(file, "A reference to file should not be NULL");
    if (!file.exists()) {
        throw new IOException("The given file " + file.getAbsolutePath() + " doesn't exist");
    }// w  w  w .j  av  a2  s .  co  m
    pushFile(remotePath, Base64.encodeBase64(FileUtils.readFileToByteArray(file)));
}