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

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

Introduction

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

Prototype

public static FileOutputStream openOutputStream(File file) throws IOException 

Source Link

Document

Opens a FileOutputStream for the specified file, checking and creating the parent directory if it does not exist.

Usage

From source file:de.crowdcode.movmvn.core.Unzipper.java

/**
 * Unzip a file.// ww  w  . j av  a  2 s . c om
 * 
 * @param archiveFile
 *            to be unzipped
 * @param outPath
 *            the place to put the result
 * @throws IOException
 *             exception
 * @throws ZipException
 *             exception
 */
public void unzipFileToDir(final File archiveFile, final File outPath) throws IOException, ZipException {
    ZipFile zipFile = new ZipFile(archiveFile);
    Enumeration<ZipArchiveEntry> e = zipFile.getEntries();
    while (e.hasMoreElements()) {
        ZipArchiveEntry entry = e.nextElement();
        File file = new File(outPath, entry.getName());
        if (entry.isDirectory()) {
            FileUtils.forceMkdir(file);
        } else {
            InputStream is = zipFile.getInputStream(entry);
            FileOutputStream os = FileUtils.openOutputStream(file);
            try {
                IOUtils.copy(is, os);
            } finally {
                os.close();
                is.close();
            }
            file.setLastModified(entry.getTime());
        }
    }
}

From source file:com.c4om.autoconf.ulysses.configanalyzer.packager.ZipConfigurationPackager.java

/**
 * This implementation compresses files into a ZIP file
 * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.packager.CompressedFileConfigurationPackager#compressFiles(java.io.File, java.util.List, java.io.File)
 *//*w ww.  j  av  a2 s .  c o  m*/
@Override
protected void compressFiles(File actualRootFolder, List<String> entries, File zipFile)
        throws FileNotFoundException, IOException {
    //We use the FileUtils method so that necessary directories are automatically created.
    FileOutputStream zipFOS = FileUtils.openOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(zipFOS);
    for (String entry : entries) {
        ZipEntry ze = new ZipEntry(entry);
        zos.putNextEntry(ze);
        FileInputStream sourceFileIN = new FileInputStream(
                actualRootFolder.getAbsolutePath() + File.separator + entry);
        IOUtils.copy(sourceFileIN, zos);
        sourceFileIN.close();
    }
    zos.closeEntry();
    zos.close();
}

From source file:com.aliyun.odps.ogg.handler.datahub.BadOperateWriterTest.java

@Test
public void testCheckFileSize() throws IOException {

    for (int i = 0; i < 2; i++) {
        String content = "hello,world";

        if (i == 1) {
            content = "hello,liangyf";
        }//w  ww  . ja v a 2s . c  o  m

        String fileName = "1.txt";

        File file = new File(fileName);

        FileOutputStream outputStream = FileUtils.openOutputStream(file);

        outputStream.write(content.getBytes());
        outputStream.flush();
        outputStream.close();

        BadOperateWriter.checkFileSize(fileName, 1);

        Assert.assertTrue(!file.exists());

        BufferedReader br = new BufferedReader(new FileReader(fileName + ".bak"));

        String line = "";
        StringBuffer buffer = new StringBuffer();
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }

        br.close();

        String fileContent = buffer.toString();

        Assert.assertEquals(content, fileContent);
    }

    FileUtils.deleteQuietly(new File("1.txt"));
    FileUtils.deleteQuietly(new File("1.txt.bak"));
}

From source file:com.textocat.textokit.morph.commons.TrainingDataWriterBase.java

@Override
public void initialize(UimaContext ctx) throws ResourceInitializationException {
    super.initialize(ctx);
    ///*from   w ww. j  a v a  2 s. c om*/
    File outputFile = new File(outputDir, TRAINING_DATA_FILENAME);
    try {
        OutputStream os = FileUtils.openOutputStream(outputFile);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "utf-8"));
        outputWriter = new PrintWriter(bw);
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}

From source file:com.norconex.collector.core.pipeline.importer.SaveDocumentStage.java

@Override
public boolean execute(ImporterPipelineContext ctx) {
    //TODO have an interface for how to store downloaded files
    //(i.e., location, directory structure, file naming)
    File workdir = ctx.getConfig().getWorkDir();
    File downloadDir = new File(workdir, "/downloads");
    if (!downloadDir.exists()) {
        try {// ww  w . jav a 2 s . c o  m
            FileUtils.forceMkdir(downloadDir);
        } catch (IOException e) {
            throw new CollectorException("Cannot create download directory: " + downloadDir, e);
        }
    }
    String path = urlToPath(ctx.getCrawlData().getReference());

    File downloadFile = new File(downloadDir, path);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Saved file: " + downloadFile);
    }
    try {
        OutputStream out = FileUtils.openOutputStream(downloadFile);
        IOUtils.copy(ctx.getDocument().getContent(), out);
        IOUtils.closeQuietly(out);

        ctx.fireCrawlerEvent(CrawlerEvent.DOCUMENT_SAVED, ctx.getCrawlData(), downloadFile);
    } catch (IOException e) {
        throw new CollectorException("Cannot save document: " + ctx.getCrawlData().getReference(), e);
    }
    return true;
}

From source file:fr.gael.dhus.util.UnZip.java

public static void unCompress(String zip_file, String output_folder)
        throws IOException, CompressorException, ArchiveException {
    ArchiveInputStream ais = null;//from  w w w.  j  a v  a  2 s  .co m
    ArchiveStreamFactory asf = new ArchiveStreamFactory();

    FileInputStream fis = new FileInputStream(new File(zip_file));

    if (zip_file.toLowerCase().endsWith(".tar")) {
        ais = asf.createArchiveInputStream(ArchiveStreamFactory.TAR, fis);
    } else if (zip_file.toLowerCase().endsWith(".zip")) {
        ais = asf.createArchiveInputStream(ArchiveStreamFactory.ZIP, fis);
    } else if (zip_file.toLowerCase().endsWith(".tgz") || zip_file.toLowerCase().endsWith(".tar.gz")) {
        CompressorInputStream cis = new CompressorStreamFactory()
                .createCompressorInputStream(CompressorStreamFactory.GZIP, fis);
        ais = asf.createArchiveInputStream(new BufferedInputStream(cis));
    } else {
        try {
            fis.close();
        } catch (IOException e) {
            LOGGER.warn("Cannot close FileInputStream:", e);
        }
        throw new IllegalArgumentException("Format not supported: " + zip_file);
    }

    File output_file = new File(output_folder);
    if (!output_file.exists())
        output_file.mkdirs();

    // copy the existing entries
    ArchiveEntry nextEntry;
    while ((nextEntry = ais.getNextEntry()) != null) {
        File ftemp = new File(output_folder, nextEntry.getName());
        if (nextEntry.isDirectory()) {
            ftemp.mkdir();
        } else {
            FileOutputStream fos = FileUtils.openOutputStream(ftemp);
            IOUtils.copy(ais, fos);
            fos.close();
        }
    }
    ais.close();
    fis.close();
}

From source file:com.thoughtworks.go.domain.FileHandler.java

public void handle(InputStream stream) throws IOException {
    FileOutputStream fileOutputStream = null;
    try {//  w  ww . ja  v a 2s .c o m
        fileOutputStream = FileUtils.openOutputStream(artifact);
        LOG.info("[Artifact File Download] [{}] Download of artifact {} started", new Date(),
                artifact.getName());
        IOUtils.copyLarge(stream, fileOutputStream);
        LOG.info("[Artifact File Download] [{}] Download of artifact {} ended", new Date(), artifact.getName());
    } finally {
        IOUtils.closeQuietly(fileOutputStream);
    }
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(artifact);
        LOG.info("[Artifact File Download] [{}] Checksum computation of artifact {} started", new Date(),
                artifact.getName());
        String artifactMD5 = md5Hex(inputStream);
        new ChecksumValidator(artifactMd5Checksums).validate(srcFile, artifactMD5, checksumValidationPublisher);
        LOG.info("[Artifact File Download] [{}] Checksum computation of artifact {} ended", new Date(),
                artifact.getName());
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:dotaSoundEditor.Helpers.PortraitFinder.java

private void buildHeroPortraits(VPKArchive vpk) {

    BufferedImage image = null;/* w w  w  .  j ava 2  s . co m*/
    for (VPKEntry entry : vpk.getEntriesForDir("resource/flash3/images/heroes/")) {
        if (entry.getType().equals("png") && !(entry.getPath().contains("selection"))) {
            File imageFile = new File(entry.getPath());

            try (FileChannel fc = FileUtils.openOutputStream(imageFile).getChannel()) {
                fc.write(entry.getData());
                image = ImageIO.read(imageFile);
                portraitMap.put(entry.getName(), image);
            } catch (IOException ex) {
                System.err.println("Can't write " + entry.getPath() + ": " + ex.getMessage());
            }
        }
    }
}

From source file:com.izforge.izpack.installer.unpacker.Pack200FileUnpackerTest.java

@Override
protected InputStream createPackStream(File source) throws IOException {
    File tmpfile = null;/*from   w ww.  j  a v  a2 s .  c  o m*/
    JarFile jar = null;

    try {
        tmpfile = File.createTempFile("izpack-compress", ".pack200", FileUtils.getTempDirectory());
        CountingOutputStream proxyOutputStream = new CountingOutputStream(FileUtils.openOutputStream(tmpfile));
        OutputStream bufferedStream = IOUtils.buffer(proxyOutputStream);

        Pack200.Packer packer = createPack200Packer(this.packFile);
        jar = new JarFile(this.packFile.getFile());
        packer.pack(jar, bufferedStream);

        bufferedStream.flush();
        this.packFile.setSize(proxyOutputStream.getByteCount());

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copy(FileUtils.openInputStream(tmpfile), out);
        out.close();
        return new ByteArrayInputStream(out.toByteArray());
    } finally {
        if (jar != null) {
            jar.close();
        }
        FileUtils.deleteQuietly(tmpfile);
    }
}

From source file:fr.ippon.wip.config.ZipConfiguration.java

/**
 * Extract the files related to the configuration of the given name.
 * //from ww w .j a  v a2  s.c  o m
 * @param zipFile
 * @param configurationName
 * @return
 * @throws IOException
 */
private boolean extract(ZipFile zipFile, String configurationName) throws IOException {
    XMLConfigurationDAO xmlConfigurationDAO = new XMLConfigurationDAO(FileUtils.getTempDirectoryPath());
    File file;
    ZipEntry entry;
    int[] types = new int[] { XMLConfigurationDAO.FILE_NAME_CLIPPING, XMLConfigurationDAO.FILE_NAME_TRANSFORM,
            XMLConfigurationDAO.FILE_NAME_CONFIG };
    for (int type : types) {
        file = xmlConfigurationDAO.getConfigurationFile(configurationName, type);
        entry = zipFile.getEntry(file.getName());
        if (entry == null)
            return false;

        copy(zipFile.getInputStream(entry), FileUtils.openOutputStream(file));
    }

    return true;
}