Example usage for com.google.common.io FileWriteMode APPEND

List of usage examples for com.google.common.io FileWriteMode APPEND

Introduction

In this page you can find the example usage for com.google.common.io FileWriteMode APPEND.

Prototype

FileWriteMode APPEND

To view the source code for com.google.common.io FileWriteMode APPEND.

Click Source Link

Document

Specifies that writes to the opened file should append to the end of the file.

Usage

From source file:net.thangbui.cql_exporter.TableExporter.java

static void genDML(SchemaExporter generator, TableMetadata table, File file)
        throws IOException, ExecutionException, InterruptedException {
    String tableName = Utils.escapeReservedWord(table.getName());
    String keyspaceName = table.getKeyspace().getName();
    CharSink charSink = Files.asCharSink(file, Charset.defaultCharset(), FileWriteMode.APPEND);

    System.out.printf("-----------------------------------------------" + Main.LINE_SEPARATOR);
    System.out.printf("Extract from %s.%s" + Main.LINE_SEPARATOR, keyspaceName, tableName);

    if (generator.truncate) {
        charSink.write(QueryBuilder.truncate(keyspaceName, tableName).getQueryString());
    }// www  . j ava2s. c  om

    Row firstRow = getFirstRow(generator.session, tableName, keyspaceName);

    if (firstRow == null) {
        return;
    }

    final List<String> colNames = new ArrayList();
    final List<TypeCodec> typeCodecs = new ArrayList();
    List<ColumnDefinitions.Definition> definitions = firstRow.getColumnDefinitions().asList();

    for (ColumnDefinitions.Definition definition : definitions) {
        String colName = definition.getName();
        DataType type = definition.getType();
        colNames.add(Utils.escapeReservedWord(colName));
        Object object = firstRow.getObject(colName);
        typeCodecs.add(object != null ? CODEC_REGISTRY.codecFor(type, object) : CODEC_REGISTRY.codecFor(type));
    }

    String prefix = "INSERT INTO " + keyspaceName + "." + tableName + " (" + Joiner.on(',').join(colNames)
            + ") VALUES (";
    String postfix = generator.merge ? ") IF NOT EXISTS;" : ");";

    long totalNoOfRows = getTotalNoOfRows(generator.session, tableName, keyspaceName);
    System.out.printf("Total number of record: %s" + Main.LINE_SEPARATOR, totalNoOfRows);

    int count = 0;
    Select select = QueryBuilder.select().all().from(keyspaceName, tableName).allowFiltering();
    select.setFetchSize(SchemaExporter.FETCH_SIZE);
    ResultSet resultSet = generator.session.execute(select);
    Iterator<Row> iterator = resultSet.iterator();

    System.out.printf("Start write \"%s\" data DML to %s" + Main.LINE_SEPARATOR, tableName,
            file.getCanonicalPath());

    int noOfStep = getNoOfStep(totalNoOfRows);
    long step = totalNoOfRows / noOfStep;
    int stepCount = 0;

    while (iterator.hasNext()) {
        Row next = iterator.next();
        String statement = generateInsertFromRow(typeCodecs, prefix, postfix, next) + Main.LINE_SEPARATOR;
        charSink.write(statement);
        count++;
        if (totalNoOfRows > SchemaExporter.FETCH_SIZE && count > stepCount * step) {
            float v = (float) count / (float) totalNoOfRows * 100;
            System.out.printf("Done %.2f%%" + Main.LINE_SEPARATOR, v);
            stepCount++;
        }
    }
    System.out.printf("Done exporting \"%s\", total number of records exported: %s" + Main.LINE_SEPARATOR,
            tableName, count);
}

From source file:org.sosy_lab.cpachecker.appengine.io.DataStoreByteSink.java

@Override
public OutputStream openStream() throws IOException {
    OutputStream out = file.getContentOutputStream();

    if (Arrays.asList(mode).contains(FileWriteMode.APPEND)) {
        out.write(file.getContent().getBytes());
    }//from  www  .  ja  v a  2  s. c o m

    return out;
}

From source file:org.cirdles.squid.utilities.FileUtilities.java

public static void unpackZipFile(final File archive, final File targetDirectory)
        throws ZipException, IOException {
    ZipFile zipFile = new ZipFile(archive);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        final ZipEntry zipEntry = entries.nextElement();
        if (zipEntry.isDirectory()) {
            continue;
        }//w  w  w. jav a  2 s. com
        final File targetFile = new File(targetDirectory, zipEntry.getName());
        com.google.common.io.Files.createParentDirs(targetFile);
        ByteStreams.copy(zipFile.getInputStream(zipEntry),
                com.google.common.io.Files.asByteSink(targetFile, FileWriteMode.APPEND).openStream());
    }
}

From source file:org.sosy_lab.cpachecker.appengine.io.DataStoreCharSink.java

@Override
public Writer openStream() throws IOException {
    if (charset == null) {
        charset = Charset.defaultCharset();
    }/*from   w  ww  . jav  a 2  s. co  m*/

    Writer writer = file.getContentWriter(charset);

    // write any existing content to the writer to enable appending
    if (Arrays.asList(mode).contains(FileWriteMode.APPEND)) {
        writer.write(file.getContent());
    }

    return writer;
}

From source file:org.eclipse.epp.internal.logging.aeri.ui.utils.Zips.java

public static void unzip(File zipFile, File destFolder) throws IOException {
    ZipInputStream zis = null;/*from   w w  w . j  a  v a  2  s . c om*/
    try {
        zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                final File file = new File(destFolder, entry.getName());
                Files.createParentDirs(file);
                Files.asByteSink(file, FileWriteMode.APPEND).writeFrom(zis);
            }
        }
    } finally {
        Closeables.close(zis, true);
    }
}

From source file:com.infinities.skyport.util.PemLoader.java

public void savePem(String directory, String keypairName, String privateKey) throws IOException {
    String fileLocation = directory + keypairName + PEM;
    logger.info("pem loaded from: {}", fileLocation);
    Files.asCharSink(new File(fileLocation), Charsets.US_ASCII, FileWriteMode.APPEND).write(privateKey);
}

From source file:net.thangbui.cql_exporter.SchemaExporter.java

private void extractOnlyOneTable(KeyspaceMetadata keyspace) throws Exception {
    File file = FileUtils.verify(filePath, force);

    if (!noddl) {
        System.out.println("Write \"" + tableName + "\" DDL to " + file.getCanonicalPath());
        Files.asCharSink(file, Charset.defaultCharset(), FileWriteMode.APPEND)
                .write(TableExporter.genDDL(keyspace.getTable(tableName)));
    }//from   w w  w  .j  a v a  2s .co  m
    if (!nodml) {
        TableExporter.genDML(this, keyspace.getTable(tableName), file);
    }
}

From source file:org.richfaces.resource.optimizer.resource.writer.impl.ResourceWriterImpl.java

public void writePackedResource(String packName, String skinName, Resource resource) throws IOException {

    final String requestPath = resource.getRequestPath();
    String extension = getExtension(requestPath);
    String packFileName = packName + "." + extension;
    ResourceKey resourceKey = new ResourceKey(resource.getResourceName(), resource.getLibraryName());

    if (!"js".equals(extension) && !"css".equals(extension)) {
        writeResource(skinName, resource);
        return;//from  w  ww  .j  a va 2 s. com
    }

    if (!resourcesWithKnownOrder.contains(resourceKey)) {
        writeResource(skinName, resource);
        return;
    }

    String requestPathWithSkinVariable = "packed/" + packFileName;
    if (skinName != null && skinName.length() > 0) {
        requestPathWithSkinVariable = ResourceSkinUtils
                .prefixPathWithSkinPlaceholder(requestPathWithSkinVariable);
    }
    String requestPathWithSkin = Constants.SLASH_JOINER.join(skinName, "packed", packFileName);
    ResourceProcessor matchingProcessor = getMatchingResourceProcessor(requestPathWithSkin);

    OutputStream outputStream;
    synchronized (PACKED) {
        String packagingCacheKey = extension + ":" + skinName;
        if (!PACKED.containsKey(packagingCacheKey)) {
            File outFile = createOutputFile(requestPathWithSkin);
            log.debug("Opening shared output stream for " + outFile);
            outputStream = Files.asByteSink(outFile, FileWriteMode.APPEND).openStream();
            PACKED.put(packagingCacheKey, outputStream);
        }
        outputStream = PACKED.get(packagingCacheKey);
    }

    synchronized (outputStream) {
        matchingProcessor.process(requestPathWithSkin, resource.getInputStream(), outputStream, false);
    }

    processedResources.put(ResourceUtil.getResourceQualifier(resource), requestPathWithSkinVariable);
    packedResources.add(resourceKey);

    // when packaging JSF's JavaScript, make sure both compressed and uncompressed are written to static mappings
    if (ResourceUtil.isSameResource(resource, ResourceConstants.JSF_UNCOMPRESSED)
            || ResourceUtil.isSameResource(resource, ResourceConstants.JSF_COMPRESSED)) {
        processedResources.put(ResourceUtil.getResourceQualifier(ResourceConstants.JSF_COMPRESSED),
                requestPathWithSkinVariable);
        processedResources.put(ResourceUtil.getResourceQualifier(ResourceConstants.JSF_UNCOMPRESSED),
                requestPathWithSkinVariable);
    }
}

From source file:fr.ens.transcriptome.aozan.fastqscreen.FastqScreenGenomeMapper.java

/**
 * Add the genome of the sample in the file which does correspondence with
 * reference genome.//from  w ww .jav a 2s .c o m
 * @param genomesToAdd genomes must be added in alias genomes file
 */
private void updateAliasGenomeFile(final Set<String> genomesToAdd) {

    // None genome to add
    if (genomesToAdd.isEmpty()) {
        return;
    }

    final File aliasGenomesFile = new File(
            this.properties.get(Settings.QC_CONF_FASTQSCREEN_SETTINGS_GENOMES_ALIAS_PATH_KEY));

    try {
        if (aliasGenomesFile.exists()) {

            final Writer fw = Files
                    .asCharSink(aliasGenomesFile, Globals.DEFAULT_FILE_ENCODING, FileWriteMode.APPEND)
                    .openStream();

            for (final String genomeSample : genomesToAdd) {
                fw.write(genomeSample + "=\n");
            }

            fw.flush();
            fw.close();
        }
    } catch (final IOException ignored) {
        LOGGER.warning("Writing alias genomes file failed : file can not be updated.");
    }
}

From source file:org.sosy_lab.solver.z3.Z3SmtLogger.java

private synchronized void log(String s, boolean append) {
    try {//from   w  ww .  j a  v a  2  s  . c o m
        if (append) {
            logfile.asCharSink(Charset.defaultCharset(), FileWriteMode.APPEND).write(s);
        } else {
            logfile.asCharSink(Charset.defaultCharset()).write(s);
        }
    } catch (IOException e) {
        throw new AssertionError("IO-Error in smtlogfile", e);
    }
}