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

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

Introduction

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

Prototype

public static void writeByteArrayToFile(File file, byte[] data) throws IOException 

Source Link

Document

Writes a byte array to a file creating the file if it does not exist.

Usage

From source file:com.ruesga.rview.misc.CacheHelper.java

public static void writeAccountDiffCacheFile(Context context, Account account, String name, byte[] data)
        throws IOException {
    FileUtils.writeByteArrayToFile(new File(getAccountDiffCacheDir(context, account), name), data);
}

From source file:com.hivewallet.androidclient.wallet.AddressBookProvider.java

/**
 * Resizes the provided bitmap and stores it in private storage, returning a URI to it.
 * It will be deleted on the next clean up cycle, unless marked as permanent in the mean time.  */
public static Uri storeBitmap(@Nonnull Context context, @Nonnull Bitmap bitmap) {
    if (bitmap == null)
        return null;

    Bitmap bitmapScaled = ensureReasonableSize(bitmap);
    if (bitmapScaled == null)
        return null;

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    bitmapScaled.compress(CompressFormat.PNG, 100, outStream);
    byte[] photoScaled = outStream.toByteArray();

    Uri photoUri = null;//from   w  w  w .jav  a2 s. com
    try {
        /* for some reason calling DigestUtils.sha1Hex() does not work on Android */
        String hash = new String(Hex.encodeHex(DigestUtils.sha1(photoScaled)));

        /* create photo asset and database entry */
        File dir = context.getDir(Constants.PHOTO_ASSETS_FOLDER, Context.MODE_PRIVATE);
        File photoAsset = new File(dir, hash + ".png");
        photoUri = Uri.fromFile(photoAsset);
        boolean alreadyPresent = AddressBookProvider.insertOrUpdatePhotoUri(context, photoUri);
        if (!alreadyPresent) {
            FileUtils.writeByteArrayToFile(photoAsset, photoScaled);
            log.info("Saved photo asset with uri {}", photoUri);
        }

        /* use opportunity to clean up photo assets */
        List<Uri> stalePhotoUris = AddressBookProvider.deleteStalePhotoAssets(context);
        for (Uri stalePhotoUri : stalePhotoUris) {
            File stalePhotoAsset = new File(stalePhotoUri.getPath());
            FileUtils.deleteQuietly(stalePhotoAsset);
            log.info("Deleting stale photo asset with uri {}", stalePhotoUri);
        }
    } catch (IOException ignored) {
    }

    return photoUri;
}

From source file:com.t3.model.AssetLoader.java

protected void storeIndexFile(String repository, byte[] data) throws IOException {
    File file = getRepoIndexFile(repository);
    FileUtils.writeByteArrayToFile(file, data);
}

From source file:gov.nih.nci.firebird.web.common.Struts2UploadedFileInfoTest.java

@Test
public void testResolveContentTypeWithSystem() throws IOException {
    FileUtils.writeByteArrayToFile(file, new byte[10]);
    ServletContext ctx = mock(ServletContext.class);
    info.setDataFileName("funny.extention");
    assertNull(ctx.getMimeType(info.getDataFileName()));
    info.resolveContentType(ctx);/*from w ww  . j  a v  a2 s  .c om*/
    assertEquals("application/octet-stream", info.getDataContentType());
}

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

/**
 * Create destination file locally, then run download.
 * @throws Exception if anything went wrong
 *//*ww w  . j av a2s . c om*/
@Test
public void downloadOnlyIfNewerReDownloadIfFileExists() throws Exception {
    File testFile = new File(folder.getRoot(), TEST_FILE_NAME);
    FileUtils.writeByteArrayToFile(destFile, contents);
    assertTrue(destFile.setLastModified(testFile.lastModified()));
    assertTaskSuccess(download(new Parameters(singleSrc, dest, true, false)));
}

From source file:com.googlecode.dex2jar.v3.Dex2jar.java

private void saveTo(byte[] data, String name, Object dist) throws IOException {
    if (dist instanceof ZipOutputStream) {
        ZipOutputStream zos = (ZipOutputStream) dist;
        ZipEntry entry = new ZipEntry(name + ".class");
        int i = name.lastIndexOf('/');
        if (i > 0) {
            check(name.substring(0, i), zos);
        }//from w w  w . jav a 2 s  .  c om
        zos.putNextEntry(entry);
        zos.write(data);
        zos.closeEntry();
    } else {
        File dir = (File) dist;
        FileUtils.writeByteArrayToFile(new File(dir, name + ".class"), data);
    }
}

From source file:com.eulogix.kettle.steps.binary_file_output.BinaryFileOutputStep.java

/**
 * Once the transformation starts executing, the processRow() method is called repeatedly
 * by PDI for as long as it returns true. To indicate that a step has finished processing rows
 * this method must call setOutputDone() and return false;
 * //from   ww  w.  ja v a 2 s .  c  o  m
 * Steps which process incoming rows typically call getRow() to read a single row from the
 * input stream, change or add row content, call putRow() to pass the changed row on 
 * and return true. If getRow() returns null, no more rows are expected to come in, 
 * and the processRow() implementation calls setOutputDone() and returns false to
 * indicate that it is done too.
 * 
 * Steps which generate rows typically construct a new row Object[] using a call to
 * RowDataUtil.allocateRowData(numberOfFields), add row content, and call putRow() to
 * pass the new row on. Above process may happen in a loop to generate multiple rows,
 * at the end of which processRow() would call setOutputDone() and return false;
 * 
 * @param smi the step meta interface containing the step settings
 * @param sdi the step data interface that should be used to store
 * 
 * @return true to indicate that the function should be called again, false if the step is done
 */
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {

    // safely cast the step settings (meta) and runtime info (data) to specific implementations 
    BinaryFileOutputStepMeta meta = (BinaryFileOutputStepMeta) smi;
    BinaryFileOutputStepData data = (BinaryFileOutputStepData) sdi;

    // get incoming row, getRow() potentially blocks waiting for more rows, returns null if no more rows expected
    Object[] r = getRow();

    // if no more rows are expected, indicate step is finished and processRow() should not be called again
    if (r == null) {
        setOutputDone();
        return false;
    }

    // the "first" flag is inherited from the base step implementation
    // it is used to guard some processing tasks, like figuring out field indexes
    // in the row structure that only need to be done once
    if (first) {
        first = false;
        // clone the input row structure and place it in our data object
        data.outputRowMeta = (RowMetaInterface) getInputRowMeta().clone();
        // use meta.getFields() to change it, so it reflects the output row structure 
        meta.getFields(data.outputRowMeta, getStepname(), null, null, this, null, null);
    }

    Object[] outputRow;

    try {
        String completePath = getFieldValue(r, meta.fields.get("folder").toString()).toString() + File.separator
                + getFieldValue(r, meta.fields.get("fileName").toString()).toString();

        FileUtils.writeByteArrayToFile(new File(completePath),
                (byte[]) getFieldValue(r, meta.fields.get("fileContent").toString()));
        outputRow = RowDataUtil.addValueData(r, data.outputRowMeta.size() - 1, true);
    } catch (IOException e) {
        e.printStackTrace();
        outputRow = RowDataUtil.addValueData(r, data.outputRowMeta.size() - 1, false);
    }

    // put the row to the output row stream
    putRow(data.outputRowMeta, outputRow);

    // log progress if it is time to to so
    if (checkFeedback(getLinesRead())) {
        logBasic("Linenr " + getLinesRead()); // Some basic logging
    }

    // indicate that processRow() should be called again
    return true;
}

From source file:com.frostwire.android.LollipopFileSystem.java

@Override
public boolean write(File file, byte[] data) {
    try {/*from w w w . jav a 2  s  .c  o  m*/
        FileUtils.writeByteArrayToFile(file, data);
        return true;
    } catch (IOException e) {
        // ignore
    }

    DocumentFile f = getFile(app, file, true);

    if (f == null) {
        LOG.error("Unable to obtain document for file: " + file);
        return false;
    }

    return write(app, f, data);
}

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

public FileManagerResponse deployFile(final FileManagerRequest request) throws FileManagerException {
    final String methodName = IFileManagerProcessor.CNAME
            + "#deployFile(final FileManagerRequest request) throws FileManagerException";

    if (DEBUG) {//from  ww w .j  a  v  a  2s  .co m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileManagerRequest: {}", request);
    }

    FileManagerResponse response = new FileManagerResponse();

    try {
        boolean isSourceList = ((request.getSourceFiles() != null) && (request.getSourceFiles().size() != 0));
        boolean isTargetList = ((request.getTargetFiles() != null) && (request.getTargetFiles().size() != 0));
        boolean sourceMatchesTarget = request.getSourceFiles().size() == request.getTargetFiles().size();

        if (DEBUG) {
            DEBUGGER.debug("isSourceList: {}", isSourceList);
            DEBUGGER.debug("isTargetList: {}", isTargetList);
            DEBUGGER.debug("sourceMatchesTarget: {}", sourceMatchesTarget);
        }

        if ((isSourceList) && (isTargetList)) {
            List<String> failedFiles = new ArrayList<String>();

            for (int x = 0; x < request.getSourceFiles().size(); x++) {
                byte[] sourceFile = request.getSourceFiles().get(x);
                String targetFile = FileUtils.getFile(request.getTargetFiles().get(x)).getName();
                String targetPath = FileUtils.getFile(request.getTargetFiles().get(x)).getParent();

                if (DEBUG) {
                    DEBUGGER.debug("sourceFile: {}", sourceFile);
                    DEBUGGER.debug("targetPath: {}", targetPath);
                    DEBUGGER.debug("targetFile: {}", targetFile);
                }

                boolean canWrite = (FileUtils.getFile(targetPath).exists())
                        ? FileUtils.getFile(targetPath).canWrite()
                        : FileUtils.getFile(targetPath).mkdirs();

                if (DEBUG) {
                    DEBUGGER.debug("canWrite: {}", canWrite);
                }

                if (canWrite) {
                    FileUtils.writeByteArrayToFile(FileUtils.getFile(targetPath, targetFile), sourceFile);

                    if (!(FileUtils.sizeOf(FileUtils.getFile(targetPath, targetFile)) == request
                            .getSourceFiles().get(x).length)) {
                        ERROR_RECORDER.error(
                                "Failed to properly write file " + targetFile + " to path " + targetPath);

                        FileUtils.deleteQuietly(FileUtils.getFile(targetPath, targetFile));

                        failedFiles.add(targetFile);
                    }
                } else {
                    // can't write
                    throw new FileManagerException(
                            "Cannot write to provided directory. Possible permissions problem.");
                }
            }

            if (failedFiles.size() != 0) {
                response.setRequestStatus(AgentStatus.FAILURE);
            } else {
                response.setRequestStatus(AgentStatus.SUCCESS);
            }
        } else {
            // only one file
            byte[] sourceFile = request.getFileData();
            // String targetPath = request.getFilePath();
            // String targetFile = request.getFileName();
            String targetPath = null;
            String targetFile = null;

            if (DEBUG) {
                DEBUGGER.debug("sourceFile: {}", sourceFile);
                DEBUGGER.debug("targetPath: {}", targetPath);
                DEBUGGER.debug("targetFile: {}", targetFile);
            }

            boolean canWrite = (FileUtils.getFile(targetPath).exists())
                    ? FileUtils.getFile(targetPath).canWrite()
                    : FileUtils.getFile(targetPath).mkdirs();

            if (DEBUG) {
                DEBUGGER.debug("canWrite: {}", canWrite);
            }

            if (canWrite) {
                FileUtils.writeByteArrayToFile(FileUtils.getFile(targetPath, targetFile), sourceFile);

                if (FileUtils.sizeOf(FileUtils.getFile(targetPath, targetFile)) == sourceFile.length) {
                    // match
                    response.setRequestStatus(AgentStatus.SUCCESS);
                } else {
                    FileUtils.deleteQuietly(FileUtils.getFile(targetPath, targetFile));

                    throw new FileManagerException(
                            "Unable to complete file deployment, written content does NOT match source.");
                }
            } else {
                throw new FileManagerException(
                        "Cannot write to provided directory. Possible permissions problem.");
            }
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileManagerException(iox.getMessage(), iox);
    }

    return response;
}

From source file:nc.noumea.mairie.appock.services.impl.ConfigServiceImpl.java

private void creeFichierCoteServeur(FichierDocumentationUtilisateur fichierDocumentationUtilisateur)
        throws IOException {
    if (fichierDocumentationUtilisateur.getContenu() == null) {
        return;//from   w w  w .ja v  a 2  s.c  o m
    }

    FileUtils.writeByteArrayToFile(getFileFichierDocumentationUtilisateur(fichierDocumentationUtilisateur),
            fichierDocumentationUtilisateur.getContenu());
}