Example usage for com.google.common.io Files asCharSink

List of usage examples for com.google.common.io Files asCharSink

Introduction

In this page you can find the example usage for com.google.common.io Files asCharSink.

Prototype

public static CharSink asCharSink(File to, Charset charset) 

Source Link

Usage

From source file:org.nmdp.ngs.align.Blastn.java

/**
 * Return the high-scoring segment pairs (HSPs) from blastn of the source and target sequence files in FASTA format.
 *
 * @param sourceFile source sequence file in FASTA format, must not be null
 * @param targetFile target sequence file in FASTA format, must not be null
 * @return zero or more high-scoring segment pairs (HSPs) from blastn of the source and target sequence files
 *    in FASTA format// w  w  w .j  ava 2 s .com
 * @throws IOException if an I/O error occurs
 */
public static Iterable<HighScoringPair> blastn(final File sourceFile, final File targetFile)
        throws IOException {
    checkNotNull(sourceFile);
    checkNotNull(targetFile);

    File blastResult = File.createTempFile("blastn", ".txt");

    // blastn can't handle compressed files, so copy source and target to temp files, decompressing if necessary
    File sourceFileCopy = File.createTempFile("sourceFile", ".fa");
    charSource(sourceFile).copyTo(Files.asCharSink(sourceFileCopy, Charset.forName("UTF-8")));

    File targetFileCopy = File.createTempFile("targetFile", ".fa");
    charSource(targetFile).copyTo(Files.asCharSink(targetFileCopy, Charset.forName("UTF-8")));

    ProcessBuilder blastn = new ProcessBuilder("blastn", "-subject", sourceFileCopy.getPath(), "-query",
            targetFileCopy.getPath(), "-outfmt", "6", "-out", blastResult.getPath());
    Process blastnProcess = blastn.start();
    try {
        blastnProcess.waitFor();
    } catch (InterruptedException e) {
        // ignore
    }

    BufferedReader reader = null;
    List<HighScoringPair> hsps = Lists.newLinkedList();
    try {
        reader = new BufferedReader(new FileReader(blastResult));
        for (HighScoringPair hsp : HspReader.read(reader)) {
            hsps.add(hsp);
        }
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            // empty
        }
        sourceFileCopy.delete();
        targetFileCopy.delete();
    }
    return ImmutableList.copyOf(hsps);
}

From source file:adept.mappers.thrift.io.ThriftToADEPT.java

public static void thriftDocumentToADEPT(final String thriftFile, final String adeptFile)
        throws IOException, TException {
    final thrift.adept.common.HltContentContainer thriftDocument = new thrift.adept.common.HltContentContainer();
    final byte[] serialized = adept.io.Reader.getInstance().readFileIntoByteArray(thriftFile);
    tdeserializer.deserialize(thriftDocument, serialized);
    final adept.common.HltContentContainer adeptContainer = mapper.convert(thriftDocument);
    final String adeptString = xmlSerializer.serializeAsString(adeptContainer);
    Files.asCharSink(new File(adeptFile), Charsets.UTF_8).write(adeptString);
}

From source file:org.gradle.buildinit.plugins.internal.SimpleTemplateOperation.java

@Override
public void generate() {
    try {/*from  www  .  j  ava  2s  .co m*/
        target.getParentFile().mkdirs();
        SimpleTemplateEngine templateEngine = new SimpleTemplateEngine();
        String templateText = Resources.asCharSource(templateURL, CharsetToolkit.getDefaultSystemCharset())
                .read();
        Template template = templateEngine.createTemplate(templateText);
        Writer writer = Files.asCharSink(target, Charsets.UTF_8).openStream();
        try {
            template.make(bindings).writeTo(writer);
        } finally {
            writer.close();
        }
    } catch (Exception ex) {
        throw new GradleException("Could not generate file " + target + ".", ex);
    }
}

From source file:org.gradle.api.internal.resources.FileCollectionBackedTextResource.java

public File asFile(String targetCharset) {
    Charset targetCharsetObj = Charset.forName(targetCharset);

    if (targetCharsetObj.equals(charset)) {
        return fileCollection.getSingleFile();
    }//from www  .  j  a v a  2s .co  m

    File targetFile = tempFileProvider.createTemporaryFile("fileCollection", ".txt", "resource");
    try {
        Files.asCharSource(fileCollection.getSingleFile(), charset)
                .copyTo(Files.asCharSink(targetFile, targetCharsetObj));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return targetFile;
}

From source file:org.glowroot.plugin.cassandra.CassandraWrapper.java

private static void downloadAndExtract(File baseDir) throws MalformedURLException, IOException {
    URL url = new URL("http://archive.apache.org/dist/cassandra/" + CASSANDRA_VERSION + "/apache-cassandra-"
            + CASSANDRA_VERSION + "-bin.tar.gz");
    InputStream in = url.openStream();
    File archiveFile = File.createTempFile("cassandra-" + CASSANDRA_VERSION + "-", ".tar.gz");
    Files.asByteSink(archiveFile).writeFrom(in);
    in.close();//from  w w w  .  j a va  2s .c o m
    Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP);
    archiver.extract(archiveFile, baseDir);
    archiveFile.delete();

    File cassandraDir = new File(baseDir, "apache-cassandra-" + CASSANDRA_VERSION);
    File confDir = new File(cassandraDir, "conf");
    File yamlFile = new File(confDir, "cassandra.yaml");
    String yaml = Files.toString(yamlFile, Charsets.UTF_8);
    yaml = yaml.replace("/var/lib/cassandra", cassandraDir.getAbsolutePath().replace('\\', '/'));
    Files.asCharSink(yamlFile, Charsets.UTF_8).write(yaml);

    File log4jFile = new File(confDir, "log4j-server.properties");
    String log4j = Files.toString(log4jFile, Charsets.UTF_8);
    log4j = log4j.replace("/var/log/cassandra", cassandraDir.getAbsolutePath().replace('\\', '/'));
    Files.asCharSink(log4jFile, Charsets.UTF_8).write(log4j);
}

From source file:com.q335.r49.squaredays.MainActivity.java

private void writeLogFile() {
    if (!logChanged)
        return;/*from  ww  w  .  j  a v a2s. co  m*/
    try {
        File file = new File(getFilesDir(), fLOGS);
        List<String> fullLog = CW.getWritableShapes();
        fullLog.addAll(EW.getWritableShapes());
        Files.asCharSink(file, Charsets.UTF_8).writeLines(fullLog);
        logChanged = false;
    } catch (Exception e) {
        Log.d("SquareDays", "File write error: " + e.toString());
        Toast.makeText(context, "Cannot write to internal storage", Toast.LENGTH_LONG).show();
    }
}

From source file:org.gradle.api.internal.resources.ApiTextResourceAdapter.java

@Override
public File asFile(String targetCharset) {
    try {/*from ww w  .  j  a v  a  2s. co m*/
        File file = getWrappedTextResource().getFile();
        if (file == null) {
            file = tempFileProvider.createTemporaryFile("wrappedInternalText", ".txt", "resource");
            Files.write(getWrappedTextResource().getText(), file, Charset.forName(targetCharset));
            return file;
        }
        Charset sourceCharset = getWrappedTextResource().getCharset();
        Charset targetCharsetObj = Charset.forName(targetCharset);
        if (targetCharsetObj.equals(sourceCharset)) {
            return file;
        }

        File targetFile = tempFileProvider.createTemporaryFile("uriTextResource", ".txt", "resource");
        try {
            Files.asCharSource(file, sourceCharset).copyTo(Files.asCharSink(targetFile, targetCharsetObj));
            return targetFile;
        } catch (IOException e) {
            throw new ResourceException(
                    "Could not write " + getDisplayName() + " content to " + targetFile + ".", e);
        }
    } catch (Exception e) {
        throw ResourceExceptions.readFailed(getDisplayName(), e);
    }
}

From source file:org.rf.ide.core.executor.ArgumentsFile.java

private void writeTo(final File file) throws IOException {
    if (!file.exists()) {
        file.createNewFile();//from  www  .jav a  2s  . c o  m
    }
    Files.asCharSink(file, Charsets.UTF_8).write(generateContent());
}

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

private void extractKeyspace(KeyspaceMetadata keyspace) throws Exception {
    String nameWithoutExtension = Files.getNameWithoutExtension(filePath);

    File sharedFile = null;/*from   w w w.j a va2 s.  c om*/
    if (!export2separateFiles) {
        sharedFile = FileUtils.verify(filePath, force);
    }

    if (!noddl) {
        List<String> strings = genDDL(keyspace);
        File file;
        if (export2separateFiles) {
            file = FileUtils.verify(nameWithoutExtension + "-DDL.CQL", force);
        } else {
            file = sharedFile;
        }
        System.out.println("Write DDL to " + file.getCanonicalPath());
        Files.asCharSink(file, Charset.defaultCharset()).writeLines(strings);
    }

    List<TableMetadata> tables = Lists.newArrayList(keyspace.getTables());

    if (!nodml) {
        for (int i = 0; i < tables.size(); i++) {
            TableMetadata table = tables.get(i);
            File file;
            if (export2separateFiles) {
                file = FileUtils.verify(nameWithoutExtension + "-" + tables.get(i).getName() + "-DML.CQL",
                        force);
            } else {
                file = sharedFile;
            }
            TableExporter.genDML(this, table, file);
        }
    }
}

From source file:com.technophobia.substeps.runner.SubstepsRunnerMojo.java

@Override
public void executeBeforeAllConfigs(Config masterConfig) throws MojoExecutionException {

    // write out the master config to the root data dir
    File rootDataDir = NewSubstepsExecutionConfig.getRootDataDir(masterConfig);

    File outFile = new File(rootDataDir, "masterConfig.conf");

    mkdirOrException(rootDataDir);/*from www.  j  a  v a  2 s .  c o m*/

    try {
        String renderedConfig = SubstepsConfigLoader.render(masterConfig);
        this.getLog().info("\n\n *** USING COMBINED CONFIG:\n\n" + renderedConfig + "\n\n");

        Files.asCharSink(outFile, Charset.forName("UTF-8")).write(renderedConfig);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}