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.igormaznitsa.jhexed.swing.editor.ui.dialogs.hexeditors.DialogEditSVGImageValue.java

private void buttonSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveAsActionPerformed
    final JFileChooser dlg = new JFileChooser();
    dlg.addChoosableFileFilter(new FileFilter() {

        @Override/*  w  ww  . j av a  2 s  . c  o m*/
        public boolean accept(File f) {
            return f.isDirectory() || f.getName().toLowerCase(Locale.ENGLISH).endsWith(".svg");
        }

        @Override
        public String getDescription() {
            return "SVG files (*.svg)";
        }
    });

    if (dlg.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File file = dlg.getSelectedFile();

        if (FilenameUtils.getExtension(file.getName()).isEmpty()) {
            file = new File(file.getParentFile(), file.getName() + ".svg");
        }

        if (file.exists() && JOptionPane.showConfirmDialog(this.parent,
                "Overwrite file '" + file.getAbsolutePath() + "\'?", "Overwriting",
                JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION) {
            return;
        }
        try {
            FileUtils.writeByteArrayToFile(file, this.value.getImage().getImageData());
        } catch (IOException ex) {
            Log.error("Can't write image [" + file + ']', ex);
            JOptionPane.showMessageDialog(this, "Can't save the file for error!", "IO Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

}

From source file:com.mycompany.istudy.controller.pdf.PerformancePdfController.java

/**
 * /*from  w w w .  j av a  2  s. c  o  m*/
 * All paths are loaded from properties and configured for generating process
 */
private void initAttributes() {
    student = StudentManager.getInstance().getStudent();
    allSemesterOfStudent = SemesterManager.getInstance().getAllSemesterOfStudent(student);

    final String pattern = "yyyyMMdd_hhmm";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);

    try {
        final File currentDirPath = new File(System.getProperty("user.dir"));

        IstudyProperties istudyProperties = new IstudyProperties();
        props = istudyProperties.getConfig();

        String inputDirValue = props.getProperty(istudyProperties.INPUT_DIR);
        String chartsDirValue = props.getProperty(istudyProperties.CHARTS_DIR);
        String xmlDirValue = props.getProperty(istudyProperties.XML_DIR);
        String xmlFileValue = props.getProperty(istudyProperties.XML_FILE);
        String pdfOutputValue = props.getProperty(istudyProperties.PDF_OUTPUT_DIR);

        File input = new File(currentDirPath + inputDirValue);
        if (!input.exists()) {
            input.mkdirs();
        }

        File chartsDirFile = new File(currentDirPath + chartsDirValue);
        if (!chartsDirFile.exists()) {
            chartsDirFile.mkdirs();
        }

        File pdfOutputDirFile = new File(currentDirPath + pdfOutputValue);
        if (!pdfOutputDirFile.exists()) {
            pdfOutputDirFile.mkdirs();
        }

        File xmlDirFile = new File(currentDirPath + xmlDirValue);
        if (!xmlDirFile.exists()) {
            xmlDirFile.mkdirs();
        }

        File xmlFile = new File(currentDirPath + xmlFileValue);
        if (!xmlFile.exists()) {
            xmlFile.createNewFile();
        }

        //copy fopXconf to working dir
        final String fopConfFileName = "fop.xconf";
        File dest = new File(currentDirPath + File.separator + fopConfFileName);
        if (!dest.exists()) {
            final String content = getFile(fopConfFileName);
            FileUtils.writeByteArrayToFile(dest, content.getBytes());
        }
        fopXconfPath = dest.getAbsolutePath();

        xmlFilePath = xmlFile.getAbsolutePath();
        chartsDirPath = chartsDirFile.getAbsolutePath();
        pdfFilePath = outputDir == null
                ? String.format("%s%sresult.pdf", pdfOutputDirFile.getAbsolutePath(), File.separator)
                : String.format("%s%sgenerated_performance_%s.pdf", outputDir, File.separator,
                        sdf.format(new Date()));

    } catch (Exception e) {
        LOGGER.error("System error", e);
    }
}

From source file:gov.nih.nci.firebird.service.annual.registration.AnnualRegistrationServiceBeanTest.java

@Test
public void testForm1572Pdf() throws IOException {
    AnnualRegistration registration = AnnualRegistrationFactory.getInstanceWithId().create();

    AnnualRegistrationForm1572 form = registration.getForm1572();
    form.getIrbs().add(OrganizationFactory.getInstance().create());
    form.getLabs().add(OrganizationFactory.getInstance().create());
    form.getPracticeSites().add(OrganizationFactory.getInstance().create());
    form.setPhaseOne(true);/*  w ww . j a  va 2  s  .  c  o m*/
    form.getFormType().setTemplate(form1572File);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bean.generatePdf(form, baos);
    byte[] bytes = baos.toByteArray();
    assertTrue(bytes.length > 0);

    FileUtils.writeByteArrayToFile(new File(getTestClassesDirectory() + "Annual_Form1572.pdf"), bytes);
}

From source file:com.edduarte.protbox.Protbox.java

private static void saveAllRegistries() {
    try {/*  w w  w.java  2 s  .c o  m*/
        Cipher cipher = Cipher.getInstance("AES");
        for (PairPanel c : trayApplet.getPairPanels()) {
            PReg toSerialize = c.getRegistry();

            // stops the registry, which stops the running threads and processes
            toSerialize.stop();
            File file = new File(Constants.REGISTRIES_DIR, toSerialize.id);

            // encrypt directories using the inserted password at the beginning of the application
            try (ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ObjectOutputStream stream = new ObjectOutputStream(out)) {
                stream.writeObject(toSerialize);
                stream.flush();

                byte[] data = out.toByteArray();
                cipher.init(Cipher.ENCRYPT_MODE, registriesPasswordKey);
                data = cipher.doFinal(data);

                FileUtils.writeByteArrayToFile(file, data);

            } catch (GeneralSecurityException ex) {
                logger.error("Invalid password! Registry {} not saved!", toSerialize.toString());
                ex.printStackTrace();
            }
        }
    } catch (GeneralSecurityException | IOException ex) {
        if (Constants.verbose) {
            logger.info("Error while saving registries.", ex);
        }
    }
}

From source file:com.alibaba.jstorm.cluster.StormConfig.java

public static void write_nimbus_topology_conf(Map conf, String topologyId, Map topoConf) throws IOException {
    String topologyRoot = StormConfig.masterStormdistRoot(conf, topologyId);
    String confPath = StormConfig.stormconf_path(topologyRoot);
    FileUtils.writeByteArrayToFile(new File(confPath), Utils.serialize(topoConf));
}

From source file:com.baidu.cc.ConfigLoader.java

/**
 * Write property content to local resource file.
 * /*from ww w .ja  v a 2 s .c o m*/
 * @param configItems latest configuration items
 * @param localFile loca resource file
 * @throws IOException throw all file operation exception
 */
public void writeLocal(Map<String, String> configItems, File localFile) throws IOException {
    Assert.notNull(localFile, "Property 'localFile' is null.");
    if (!localFile.exists()) {
        throw new IOException("File not exist. " + localFile.getPath());
    }

    String json = gson.toJson(configItems);
    //to byte array
    byte[] byteArray = json.getBytes(FILE_ENCODE);

    Hex encoder = new Hex();
    byteArray = encoder.encode(byteArray);

    FileUtils.writeByteArrayToFile(localFile, byteArray);
}

From source file:fr.eurecom.hybris.demogui.HybrisDemoGui.java

public void actionPerformed(ActionEvent e) {

    String cmd = e.getActionCommand();
    if (cmd.equals("Get")) {

        if (lstHybris.getSelectedIndex() >= 0) {
            try {
                System.out.println("Retrieving " + lstHybris.getSelectedValue() + "...");
                byte[] retrieved = cm.hybris.get(lstHybris.getSelectedValue());
                if (retrieved != null) {
                    JFileChooser fc = new JFileChooser(
                            System.getProperty("user.home") + File.separator + "Desktop");
                    fc.setSelectedFile(new File("RETRIEVED_" + lstHybris.getSelectedValue()));
                    int returnVal = fc.showSaveDialog(frame);
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        FileUtils.writeByteArrayToFile(file, retrieved);
                        System.out.println("Saved: " + file.getName() + ".");
                    }/*  ww  w  .j a  va 2s  . c  o m*/
                } else
                    JOptionPane.showMessageDialog(frame, "Hybris could not download the file.", "Error",
                            JOptionPane.ERROR_MESSAGE);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

    }
    if (cmd.equals("Put")) {

        JFileChooser fc = new JFileChooser(System.getProperty("user.home") + File.separator + "Desktop");
        int returnVal = fc.showOpenDialog(frame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            System.out.println("Putting: " + file.getName() + ".");
            byte[] array;
            try {
                array = FileUtils.readFileToByteArray(file);
                new Thread(cm.new BackgroundWorker(OperationType.PUT, ClientType.HYBRIS, file.getName(), array))
                        .start();
            } catch (Exception e1) {
                e1.printStackTrace();
            }

        }

    }
    if (cmd.equals("Delete")) {

        if (lstHybris.getSelectedIndex() >= 0) {
            new Thread(cm.new BackgroundWorker(OperationType.DELETE, ClientType.HYBRIS,
                    lstHybris.getSelectedValue(), null)).start();
            System.out.println("Removed " + lstHybris.getSelectedValue() + " from Hybris.");
        }
    }
}

From source file:gov.nih.nci.firebird.service.annual.registration.AnnualRegistrationServiceBeanTest.java

@Test
public void testForm1572PdfWithInvestigators() throws IOException {
    SubInvestigatorRegistration subinvestigatorRegistration = RegistrationFactory.getInstance()
            .createSubinvestigatorRegistration();
    profile.addRegistration(subinvestigatorRegistration);

    AnnualRegistrationConfiguration configuration = AnnualRegistrationConfigurationFactory.getInstance()
            .create();/*from  w w w.ja  va 2s . c  o m*/
    AnnualRegistration registration = AnnualRegistrationFactory.getInstanceWithId().create(profile,
            configuration);

    AnnualRegistrationForm1572 form = registration.getForm1572();
    form.getIrbs().add(OrganizationFactory.getInstance().create());
    form.getLabs().add(OrganizationFactory.getInstance().create());
    form.getPracticeSites().add(OrganizationFactory.getInstance().create());

    form.getFormType().setTemplate(form1572File);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bean.generatePdf(registration.getForm1572(), baos);
    byte[] bytes = baos.toByteArray();
    assertTrue(bytes.length > 0);

    FileUtils.writeByteArrayToFile(
            new File(getTestClassesDirectory() + "Annual_Form1572_With_Investigators.pdf"), bytes);
}

From source file:com.netsteadfast.greenstep.util.UploadSupportUtils.java

public static String create(String system, String type, boolean isFile, byte[] datas, String showName)
        throws ServiceException, IOException, Exception {
    if (StringUtils.isBlank(type) || null == datas || StringUtils.isBlank(showName)) {
        throw new Exception("parameter is blank!");
    }/*from ww  w  . j  av  a  2s.c o m*/
    SysUploadVO upload = new SysUploadVO();
    upload.setIsFile((isFile ? YesNo.YES : YesNo.NO));
    upload.setShowName(showName);
    upload.setSystem(system);
    upload.setType(type);
    upload.setSubDir(getSubDir());
    if (isFile) {
        String uploadDir = getUploadFileDir(system, type);
        String uploadFileName = generateRealFileName(showName);
        mkdirUploadFileDir(system, type);
        File file = null;
        try {
            file = new File(uploadDir + "/" + uploadFileName);
            FileUtils.writeByteArrayToFile(file, datas);
        } catch (Exception e) {
            throw e;
        } finally {
            file = null;
        }
        upload.setFileName(uploadFileName);
    } else {
        upload.setContent(datas);
        upload.setFileName(" ");
    }
    DefaultResult<SysUploadVO> result = sysUploadService.saveObject(upload);
    if (result.getValue() == null) {
        throw new ServiceException(result.getSystemMessage().getValue());
    }
    return result.getValue().getOid();
}

From source file:de.xirp.mail.MailManager.java

/**
 * Exports the corresponding// w ww. ja v a  2s.  c om
 * {@link de.xirp.mail.Mail} for the given
 * {@link de.xirp.mail.MailDescriptor} to the given
 * path. A new folder is created there, the folder will contain
 * the content of the mail: text and attachments.
 * 
 * @param path
 *            The path to export the mail to.
 * @param md
 *            The mail descriptor for the mail to export.
 * @throws SerializationException
 *             if something wnt wrong while loading the mail.
 * @throws IOException
 *             if something went wrong while loading the mail.
 * @see de.xirp.mail.MailDescriptor
 */
public static void exportMail(String path, MailDescriptor md) throws SerializationException, IOException {

    Mail mail = getMail(md);
    File outputFolder = new File(path, "mailexport_" //$NON-NLS-1$
            + md.getDescriptorKey());

    File tempDir = new File(Constants.TMP_DIR);
    File tempOutputFolder = new File(tempDir, "xirpmailexport"); //$NON-NLS-1$
    tempOutputFolder.mkdir();

    File text = new File(tempOutputFolder, "mail.txt"); //$NON-NLS-1$
    text.createNewFile();

    /* write mailtext, encoding is Unicode */
    FileUtils.writeStringToFile(text,
            mail.getSubject() + Constants.LINE_SEPARATOR + Constants.LINE_SEPARATOR + mail.getText(),
            "Unicode"); //$NON-NLS-1$

    File attachmentFolder = new File(tempOutputFolder, "attachments"); //$NON-NLS-1$
    attachmentFolder.mkdir();

    for (Attachment a : mail.getAttachments()) {
        File attachment = new File(attachmentFolder, a.getFileName());
        attachment.createNewFile();
        FileUtils.writeByteArrayToFile(attachment, a.getAttachmentFileContent());
    }

    FileUtils.copyDirectory(tempOutputFolder, outputFolder);
}