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

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

Introduction

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

Prototype

public static void write(CharSequence from, File to, Charset charset) throws IOException 

Source Link

Usage

From source file:org.obeonetwork.dsl.uml2.usage.analytics.SiriusEditorsListener.java

private String retrieveMarker(String found) throws IOException {
    IPath path = Platform.getStateLocation(UsageActivator.getDefault().getBundle());
    if (path != null) {
        path = path.append("hostname");
        if (!path.toFile().exists()) {
            Files.write(found, path.toFile(), Charset.forName("UTF-8"));
        } else {//from   w w  w .  java2  s  . c  om
            if (path.toFile().canRead()) {
                return Files.readFirstLine(path.toFile(), Charset.forName("UTF-8"));
            }
        }
    }
    return found;
}

From source file:org.apache.flink.api.java.tuple.TupleGenerator.java

private static void insertCodeIntoFile(String code, File file) throws IOException {
    String fileContent = Files.toString(file, StandardCharsets.UTF_8);

    try (Scanner s = new Scanner(fileContent)) {
        StringBuilder sb = new StringBuilder();
        String line;/*from ww w.j a  va 2s .  c  o m*/

        boolean indicatorFound = false;

        // add file beginning
        while (s.hasNextLine() && (line = s.nextLine()) != null) {
            sb.append(line).append("\n");
            if (line.contains(BEGIN_INDICATOR)) {
                indicatorFound = true;
                break;
            }
        }

        if (!indicatorFound) {
            System.out.println("No indicator found in '" + file + "'. Will skip code generation.");
            s.close();
            return;
        }

        // add generator signature
        sb.append("\t// GENERATED FROM ").append(TupleGenerator.class.getName()).append(".\n");

        // add tuple dependent code
        sb.append(code).append("\n");

        // skip generated code
        while (s.hasNextLine() && (line = s.nextLine()) != null) {
            if (line.contains(END_INDICATOR)) {
                sb.append(line).append("\n");
                break;
            }
        }

        // add file ending
        while (s.hasNextLine() && (line = s.nextLine()) != null) {
            sb.append(line).append("\n");
        }
        s.close();
        Files.write(sb.toString(), file, StandardCharsets.UTF_8);
    }
}

From source file:org.dllearner.algorithms.qtl.experiments.BenchmarkDescriptionGeneratorHTML.java

public void generateBenchmarkDescription(File inputFile, File htmlOutputFile, boolean withQueryIdGivenInFile)
        throws Exception {
    sb = new StringBuilder();

    generateBenchmarkDescription(inputFile, withQueryIdGivenInFile);

    try {/*from   w w w  . ja  va2 s.c  om*/
        Files.write(sb, htmlOutputFile, Charsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.tekstosense.segmenter.StructurePdf.PdfSections.java

public List<String> generateOutput() throws IOException {
    List<String> finalJson = new ArrayList<>();
    ObjectMapper mapper = new ObjectMapper();
    for (Entry<File, List<Section>> entry : pdfSections.entrySet()) {
        List<Structure> structures = StructureUtil.toStructure(entry.getValue());

        if (this.params.getOutputDir() != null) {
            File toFile = new File(this.params.getOutputDir(), entry.getKey().getName() + ".txt");
            Files.write(structures.toString(), toFile, Charsets.UTF_8);
        } else if (params.getFormat().equalsIgnoreCase("STDOUT")) {
            System.out.println(structures.toString());
        }/*from   w ww .  j av  a  2s  .c  o  m*/
        finalJson.add(mapper.writeValueAsString(structures));
    }
    return finalJson;
}

From source file:org.jetbrains.kotlin.integration.KotlinIntegrationTestBase.java

private void check(String baseName, String content) throws IOException {
    File actualFile = new File(getTestDataDir(), baseName + ".actual");
    File expectedFile = new File(getTestDataDir(), baseName + ".expected");

    String normalizedContent = normalizeOutput(content);

    if (!expectedFile.isFile()) {
        Files.write(normalizedContent, actualFile, Charsets.UTF_8);
        fail("No .expected file " + expectedFile);
    }//from w  ww.j ava 2 s.c  o  m

    try {
        JetTestUtils.assertEqualsToFile(expectedFile, normalizedContent);
        //noinspection ResultOfMethodCallIgnored
        actualFile.delete();
    } catch (ComparisonFailure e) {
        Files.write(normalizedContent, actualFile, Charsets.UTF_8);
        throw e;
    }
}

From source file:org.apache.kudu.gradle.DistTestTask.java

@TaskAction
public void doStuff() throws IOException {
    getProject().delete(outputDir);/*from ww  w. j  a  v  a2s.  c  o m*/
    getProject().mkdir(outputDir);
    List<String> baseDeps = getBaseDeps();
    for (Test t : testTasks) {
        List<String> testClassNames = collectTestNames(t);
        for (String c : testClassNames) {
            File isolateFile = new File(outputDir, c + ".isolate");
            File isolatedFile = new File(outputDir, c + ".isolated");
            File genJsonFile = new File(outputDir, c + ".gen.json");

            Files.write(genIsolate(outputDir.toPath(), t, c, baseDeps), isolateFile, UTF_8);

            // Write the gen.json
            GenJson gen = new GenJson();
            gen.args = ImmutableList.of("-i", isolateFile.toString(), "-s", isolatedFile.toString());
            gen.dir = outputDir.toString();
            gen.name = c;
            Files.write(GSON.toJson(gen), genJsonFile, UTF_8);
        }
    }
}

From source file:com.github.tomakehurst.wiremock.common.AbstractFileSource.java

private void writeTextFileAndTranslateExceptions(String contents, File toFile) {
    try {/*from   www  .  j av a  2 s . c  om*/
        Files.write(contents, toFile, UTF_8);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:eu.numberfour.n4js.antlr.internal.AntlrCodeQualityHelper.java

/**
 * Remove duplicate bitset declarations to reduce the size of the static initializer but keep the bitset
 * FOLLOW_ruleExpression_in_ruleExpressionStatement with a simplified name.
 *///from   w w  w . j av  a  2  s . co m
public static void removeDuplicateBitsets(String javaFile, Charset encoding) {
    try {
        //
        String content = Files.toString(new File(javaFile), encoding);
        StringBuilder newContent = new StringBuilder(content.length());
        Matcher matcher = bitsetPattern.matcher(content);
        int offset = 0;
        Map<String, String> bitsets = Maps.newHashMap();
        Map<String, String> namesToReplace = Maps.newHashMap();
        while (matcher.find(offset)) {
            String originalFieldName = matcher.group(1);
            String synthesizedFieldName = "FOLLOW_" + (bitsets.size() + 1);
            String bitset = matcher.group(2);
            String existing = bitsets.putIfAbsent(bitset, synthesizedFieldName);
            if (existing == null) {
                existing = synthesizedFieldName;
                newContent.append(content, offset, matcher.start(1));
                newContent.append(synthesizedFieldName);
                newContent.append(" = ");
                newContent.append(bitset);
            }
            namesToReplace.put(originalFieldName, existing);
            if (originalFieldName.startsWith("FOLLOW_ruleExpression_in_ruleExpressionStatement")) {
                newContent.append(content, offset, matcher.start(1));
                newContent.append("FOLLOW_ruleExpression_in_ruleExpressionStatement = ");
                newContent.append(existing);
            }
            offset = matcher.end(2);
        }
        newContent.append(content, offset, content.length());
        content = newContent.toString();
        newContent = new StringBuilder(content.length());
        String rawFollowPattern = "\\bFOLLOW_\\w+\\b";
        Pattern followPattern = Pattern.compile(rawFollowPattern);
        Matcher followMatcher = followPattern.matcher(content);
        Set<String> doNotReplace = Sets.newHashSet(bitsets.values());
        doNotReplace.add("FOLLOW_ruleExpression_in_ruleExpressionStatement");
        offset = 0;
        while (followMatcher.find(offset)) {
            String replaceMe = followMatcher.group();
            String replaceBy = namesToReplace.get(replaceMe);
            if (replaceBy == null) {
                if (!doNotReplace.contains(replaceMe))
                    throw new IllegalStateException(replaceMe);
                replaceBy = replaceMe;
            }
            newContent.append(content, offset, followMatcher.start());
            newContent.append(replaceBy);
            offset = followMatcher.end();
        }
        newContent.append(content, offset, content.length());
        Files.write(newContent, new File(javaFile), encoding);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.oneandone.maven.plugins.cycles.analyzer.ComponentAnalyzer.java

private void writeCycleGraph(DirectedGraph<String, WeightedEdge> component) throws IOException {
    if (!writeDotFiles) {
        return;/*  www .  j  a  v  a2  s .c om*/
    }
    File dotFile = new File(classDir.getParent(), "graph-" + cycleCount + ".dot");
    String dotString = GraphDotUtils.toDot(component, shorten);
    Files.write(dotString, dotFile, Charsets.UTF_8);
}

From source file:org.spongepowered.common.util.SpongeUsernameCache.java

/**
 * Save the cache to file//from  w  w  w .  j  a va  2 s  .c  o  m
 */
public static void save() {
    if (!loaded) {
        load();
    }

    try {
        // Make sure we don't save when another thread is still saving
        Files.write(gson.toJson(map), saveFile, charset);
    } catch (IOException e) {
        SpongeImpl.getLogger().error("Failed to save username cache to file!", e);
    }
}