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.edduarte.protbox.core.Constants.java

/**
 * Moves all contents from the first specified registry to the second specified
 * registry, overriding if it already exists!
 *//*from   w w  w  . java 2  s  .c  om*/
public static void moveContentsFromDirToDir(File fromDir, File toDir) throws IOException {
    try {
        File[] list = fromDir.listFiles();
        if (list == null) {
            return;
        }
        for (File f : list) {
            File destination = new File(toDir, f.getName());
            if (f.isDirectory()) {
                destination.mkdir();
                moveContentsFromDirToDir(f, destination);
            } else {
                FileUtils.writeByteArrayToFile(destination, FileUtils.readFileToByteArray(f));
            }
            Constants.delete(f);
        }
    } catch (NullPointerException ex) {
        throw new IOException("Specified registry is not a folder.", ex);
    }
}

From source file:com.opencart.controller.ProductController.java

@RequestMapping(value = "/product/upload", method = RequestMethod.POST)
public @ResponseBody ModelAndView handleFileUpload(@RequestParam("id") String id,
        @RequestParam("file") MultipartFile image, HttpServletRequest request) {
    if (!image.isEmpty()) {
        try {/*  w w w  . j a v a  2 s  .  com*/
            File file = new File("c:/uploads/products/" + id + "/" + image.getOriginalFilename());

            FileUtils.writeByteArrayToFile(file, image.getBytes());
            Product product = productService.getById(Long.parseLong(id));
            product.setImg(file.getName());
            productService.update(product);

            List<Product> products = productService.list();
            ModelAndView mv = new ModelAndView("admin/product", "products", products);
            return mv;

        } catch (Exception e) {
            ModelAndView mv = new ModelAndView("admin/addProductImage");
            mv.addObject("id", id);
            return mv;
        }
    } else {
        ModelAndView mv = new ModelAndView("admin/addProductImage");
        mv.addObject("id", id);
        return mv;
    }
}

From source file:com.edgenius.wiki.ext.textnut.BPListParaserHandler.java

public void endElement(String uri, String localName, String qName) throws SAXException {
    if (qName.equals("key")) {
        String content = StringUtils.trim(characters.toString());
        if ("WebMainResource".equals(content)) {
            mainResource = 1;/*from  w  w w. j a  v a 2  s . co  m*/
        } else if ("WebSubresources".equals(content)) {
            mainResource = 2;
        } else if ("WebResourceURL".equals(content)) {
            tagFlag = 2;
        } else if ("WebResourceData".equals(content)) {
            tagFlag = 5;
        } else {
            //other
            tagFlag = 0;
        }
        return;
    }
    if (qName.equals("string")) {
        if (tagFlag == 2) {
            url = StringUtils.trim(characters.toString());
        }
    }

    if (tagFlag == 5 && qName.equals("data")) {
        File file = new File(fileCacheDir, FileUtil.getFileName(url));
        //Attachments
        if (url != null) {
            try {
                if (mainResource == 1) {
                    //HTML
                    url = NutParser.MAIN_RESOURCE_URL;
                }
                FileUtils.writeByteArrayToFile(file,
                        Base64.decodeBase64(characters.toString().trim().getBytes()));
                //cache to return map
                files.put(url, file);
            } catch (IOException e) {
                log.error("Unable to write attachment for BPList", e);
            }
        } else {
            log.error("Null URL for file resource in BPList");
        }
    }

}

From source file:net.nicholaswilliams.java.licensing.encryption.TestFilePublicKeyDataProvider.java

@Test
@Ignore("canRead()/canWrite() do not work on Win; setReadable()/setWritable() do not work on some Macs.")
public void testGetEncryptedPublicKeyData02() throws IOException {
    final String fileName = "testGetEncryptedPublicKeyData02.key";
    File file = new File(fileName);
    file = file.getCanonicalFile();//from w  ww. j  a  v  a 2  s  .  c o m

    if (file.exists())
        FileUtils.forceDelete(file);

    byte[] data = new byte[] { 0x01, 0x71, 0x33 };

    FileUtils.writeByteArrayToFile(file, data);

    try {
        assertTrue("Setting the file to not-readable should have succeeded.", file.setReadable(false, false));
        assertFalse("The file should not be readable.", file.canRead());
        assertTrue("The file should still be writable.", file.canWrite());

        FilePublicKeyDataProvider provider = new FilePublicKeyDataProvider(file);

        try {
            provider.getEncryptedPublicKeyData();
            fail("Expected exception KeyNotFoundException.");
        } catch (KeyNotFoundException e) {
            assertNotNull("The cause should not be null.", e.getCause());
        }
    } finally {
        FileUtils.forceDelete(file);
    }
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestFilePrivateKeyDataProvider.java

@Test
@Ignore("canRead()/canWrite() do not work on Win; setReadable()/setWritable() do not work on some Macs.")
public void testGetEncryptedPrivateKeyData02() throws IOException {
    final String fileName = "testGetEncryptedPrivateKeyData02.key";
    File file = new File(fileName);
    file = file.getCanonicalFile();// w  w  w  .j  a v a  2s .c  o  m

    if (file.exists())
        FileUtils.forceDelete(file);

    byte[] data = new byte[] { 0x01, 0x71, 0x33 };

    FileUtils.writeByteArrayToFile(file, data);

    try {
        assertTrue("Setting the file to not-readable should have succeeded.", file.setReadable(false, false));
        assertFalse("The file should not be readable.", file.canRead());
        assertTrue("The file should still be writable.", file.canWrite());

        FilePrivateKeyDataProvider provider = new FilePrivateKeyDataProvider(file);

        try {
            provider.getEncryptedPrivateKeyData();
            fail("Expected exception KeyNotFoundException.");
        } catch (KeyNotFoundException e) {
            assertNotNull("The cause should not be null.", e.getCause());
        }
    } finally {
        FileUtils.forceDelete(file);
    }
}

From source file:com.music.service.ManagementService.java

@ManagedOperation
@Async/*from  w  w  w  .  j  a  v  a 2 s . c  om*/
public void fillVariation() {
    List<Piece> pieces = dao.listOrdered(Piece.class, "id");
    for (Piece piece : pieces) {
        try {
            InputStream is = pieceService.getPieceMidiFile(piece.getId());
            byte[] midi = IOUtils.toByteArray(is);
            File tmp = File.createTempFile("tmp", "mid");
            FileUtils.writeByteArrayToFile(tmp, midi);
            Score score = new Score();
            Read.midi(score, tmp.getAbsolutePath());
            double variation = MainPartGenerator.calculateVariation(score.getPart(0));
            piece.setVariation(variation);
            pieceService.save(piece);
            tmp.delete();
        } catch (Exception ex) {
            logger.error("Problem seting variety", ex);
        }

    }
}

From source file:ips1ap101.ejb.business.process.logic.impl.ArchivoAdjuntoBusinessProcessLogicImpl.java

/**
 * SYNCHRONOUS INSTANCE PROCESS restaurarArchivoServidorWeb.
 * <p>//w  w  w  .  j  ava2s. c  o m
 * restaura el archivo del servidor web con el contenido del archivo almacenado en el servidor de base de datos
 */
@Override
public void restaurarArchivoServidorWeb(ArchivoAdjuntoRestaurarArchivoServidorWebMessage message,
        ArchivoAdjunto instance) throws Exception {
    if (message == null) {
        throw new IllegalArgumentException(
                ArchivoAdjuntoRestaurarArchivoServidorWebMessage.class.getSimpleName());
    }
    if (instance == null) {
        throw new IllegalArgumentException(ArchivoAdjunto.class.getSimpleName());
    }
    deleteQuietly(instance);
    File file = new File(Utils.getAttachedFileName(instance.getArchivoServidor()));
    if (file.exists()) {
        message.setCondicion(CondicionEjeFunEnumeration.EJECUTADO_CON_ERRORES);
        message.setMensaje(TLC.getBitacora().error(BundleWebui.getString("archivo_adjunto.archivo_ya_existe"),
                file.getName()));
    } else {
        FileUtils.writeByteArrayToFile(file, instance.getOctetos());
    }
}

From source file:by.logscanner.LogScanner.java

public void write() throws IOException {
    for (FileData item : fileData) {
        FileUtils.writeByteArrayToFile(new File(destPath + item.fileName), item.content);
    }//w w w.j a  v a 2s.com
}

From source file:com.bandstand.web.ImagesController.java

/**
 *  Shows you can request a parent object in the arguments list, ie ImagesRoot
 *//*from  w ww  .  j  a v  a 2s .c o m*/
@PutChild
public Image uploadImage(Image image, byte[] bytes, ImagesRoot root) throws IOException {
    System.out.println("replacing image in: " + root);
    File content = new File(image.getFileName());
    FileUtils.writeByteArrayToFile(content, bytes);
    return image;
}

From source file:com.badlogicgames.packr.Packr.java

public void pack(Config config) throws IOException {
    // create output dir
    File out = new File(config.outDir);
    File target = out;//w w  w  .j  a  v a 2 s .co m
    if (out.exists()) {
        if (new File(".").equals(out)) {
            System.out.println("Output directory equals working directory, aborting");
            System.exit(-1);
        }

        System.out.println("Output directory '" + out.getAbsolutePath() + "' exists, deleting");
        FileUtils.deleteDirectory(out);
    }
    out.mkdirs();

    Map<String, String> values = new HashMap<String, String>();
    values.put("${executable}", config.executable);
    values.put("${bundleIdentifier}", "com.yourcompany.identifier"); // FIXME add as a param

    // if this is a mac build, let's create the app bundle structure
    if (config.platform == Platform.mac) {
        new File(out, "Contents").mkdirs();
        FileUtils.writeStringToFile(new File(out, "Contents/Info.plist"),
                readResourceAsString("/Info.plist", values));
        target = new File(out, "Contents/MacOS");
        target.mkdirs();
        new File(out, "Contents/Resources").mkdirs();
        // FIXME copy icons
    }

    // write jar, exe and config to target folder
    byte[] exe = null;
    String extension = "";
    switch (config.platform) {
    case windows:
        exe = readResource("/packr-windows.exe");
        extension = ".exe";
        break;
    case linux32:
        exe = readResource("/packr-linux");
        break;
    case linux64:
        exe = readResource("/packr-linux-x64");
        break;
    case mac:
        exe = readResource("/packr-mac");
        break;
    }
    FileUtils.writeByteArrayToFile(new File(target, config.executable + extension), exe);
    new File(target, config.executable + extension).setExecutable(true);
    FileUtils.copyFile(new File(config.jar), new File(target, new File(config.jar).getName()));
    writeConfig(config, new File(target, "config.json"));

    // add JRE from local or remote zip file
    File jdkFile = null;
    if (config.jdk.startsWith("http://") || config.jdk.startsWith("https://")) {
        System.out.println("Downloading JDK from '" + config.jdk + "'");
        jdkFile = new File(target, "jdk.zip");
        InputStream in = new URL(config.jdk).openStream();
        OutputStream outJdk = FileUtils.openOutputStream(jdkFile);
        IOUtils.copy(in, outJdk);
        in.close();
        outJdk.close();
    } else {
        jdkFile = new File(config.jdk);
    }
    File tmp = new File(target, "tmp");
    tmp.mkdirs();
    System.out.println("Unpacking JRE");
    ZipUtil.unpack(jdkFile, tmp);
    File jre = searchJre(tmp);
    if (jre == null) {
        System.out.println("Couldn't find JRE in JDK, see '" + tmp.getAbsolutePath() + "'");
        System.exit(-1);
    }
    FileUtils.copyDirectory(jre, new File(target, "jre"));
    FileUtils.deleteDirectory(tmp);
    if (config.jdk.startsWith("http://") || config.jdk.startsWith("https://")) {
        jdkFile.delete();
    }

    // copy resources
    System.out.println("copying resources");
    copyResources(target, config.resources);

    // perform tree shaking      
    if (config.minimizeJre != null) {
        minimizeJre(config, target);
    }

    System.out.println("Done!");
}