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

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:com.github.rinde.jaamas17.VanLonHolvoetResultWriter.java

@Override
void appendSimResult(SimulationResult sr, File destFile) {
    final String pc = sr.getSimArgs().getScenario().getProblemClass().getId();
    final String id = sr.getSimArgs().getScenario().getProblemInstanceId();

    try {/*  w  ww . j av a 2  s.  c o  m*/
        final String scenarioName = Joiner.on("-").join(pc, id);
        final List<String> propsStrings = Files.readLines(
                new File(PerformExperiment.VANLON_HOLVOET_DATASET + scenarioName + ".properties"),
                Charsets.UTF_8);
        final Map<String, String> properties = Splitter.on("\n").withKeyValueSeparator(" = ")
                .split(Joiner.on("\n").join(propsStrings));

        final ImmutableMap.Builder<Enum<?>, Object> map = ImmutableMap.<Enum<?>, Object>builder()
                .put(OutputFields.SCENARIO_ID, scenarioName)
                .put(OutputFields.DYNAMISM, properties.get("dynamism_bin"))
                .put(OutputFields.URGENCY, properties.get("urgency"))
                .put(OutputFields.SCALE, properties.get("scale"))
                .put(OutputFields.NUM_ORDERS, properties.get("AddParcelEvent"))
                .put(OutputFields.NUM_VEHICLES, properties.get("AddVehicleEvent"))
                .put(OutputFields.RANDOM_SEED, sr.getSimArgs().getRandomSeed())
                .put(OutputFields.REPETITION, sr.getSimArgs().getRepetition());

        addSimOutputs(map, sr, objectiveFunction);

        final String line = MeasureGendreau.appendValuesTo(new StringBuilder(), map.build(), getFields())
                .append(System.lineSeparator()).toString();
        Files.append(line, destFile, Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.geogit.storage.bdbje.JEStagingDatabase.java

/**
 * Adds a conflict to the database.//from w  w w  . jav a  2  s  .c  o  m
 * 
 * @param namespace the namespace of the conflict
 * @param conflict the conflict to add
 */
@Override
public void addConflict(@Nullable String namespace, Conflict conflict) {
    Optional<File> file = findOrCreateConflictsFile(namespace);
    Preconditions.checkState(file.isPresent());
    try {
        Files.append(conflict.toString() + "\n", file.get(), Charsets.UTF_8);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.hyperiongray.rcmp.ReportExtractor.java

private void saveData(ExtractedData data) throws IOException {
    String typedOutputFile = data.getFileType() == 1 ? getOutputFile1() : getOutputFile2();
    DataKey[] columns = data.getFileType() == 1 ? OutputColumns.TYPE_1 : OutputColumns.TYPE_2;
    List<String> values = new ArrayList<String>();
    for (int i = 0; i < columns.length; i++) {
        String value = null;/* w w  w. j a  va 2  s  . c o m*/
        if (data.getData().containsKey(columns[i])) {
            value = data.getData().get(columns[i]);
        }
        values.add(value != null ? value : "");
    }
    Files.append(flatten((String[]) values.toArray(new String[0]), separator), new File(typedOutputFile),
            Charset.defaultCharset());
}

From source file:es.ehu.si.ixa.pipe.nerc.train.AbstractTrainer.java

/**
 * Cross evaluation method by iterations and cutoff. This only really makes
 * sense for GIS optimization {@code GISTrainer}.
 * @param devData//from  www. ja  v  a 2s  . c  o m
 *          the development data to do the optimization
 * @param params
 *          the parameters
 * @param evalRange
 *          the range at which perform the evaluation
 * @return the best parameters, iteration and cutoff
 * @throws IOException
 *           the io exception
 */
private List<Integer> crossEval(final String devData, final TrainingParameters params, final String[] evalRange)
        throws IOException {

    System.err.println("Cross Evaluation:");
    // lists to store best parameters
    List<List<Integer>> allParams = new ArrayList<List<Integer>>();
    List<Integer> finalParams = new ArrayList<Integer>();
    Map<String, Object> resources = null;

    // F:<iterations,cutoff> Map
    Map<List<Integer>, Double> results = new LinkedHashMap<List<Integer>, Double>();
    // maximum iterations and cutoff
    Integer cutoffParam = Integer.valueOf(params.getSettings().get(TrainingParameters.CUTOFF_PARAM));
    List<Integer> cutoffList = new ArrayList<Integer>(Collections.nCopies(cutoffParam, 0));
    Integer iterParam = Integer.valueOf(params.getSettings().get(TrainingParameters.ITERATIONS_PARAM));
    List<Integer> iterList = new ArrayList<Integer>(Collections.nCopies(iterParam, 0));

    for (int cuttOff = 0; cuttOff < cutoffList.size() + 1; cuttOff++) {
        int start = Integer.valueOf(evalRange[0]);
        int iterRange = Integer.valueOf(evalRange[1]);
        for (int iteration = start + start; iteration < iterList.size() + start; iteration += iterRange) {
            // reading data for training and test
            ObjectStream<CorpusSample> aTrainSamples = getNameStream(trainData, lang, corpusFormat);
            ObjectStream<CorpusSample> devSamples = getNameStream(devData, lang, corpusFormat);

            // dynamic creation of parameters
            params.put(TrainingParameters.ITERATIONS_PARAM, Integer.toString(iteration));
            params.put(TrainingParameters.CUTOFF_PARAM, Integer.toString(cuttOff));
            System.err.println("Trying with " + iteration + " iterations...");

            // training model
            NameModel trainedModel = NameClassifier.train(lang, null, aTrainSamples, params, getFeatures(),
                    resources);
            // evaluate model
            NameClassifier nerClassifier = new NameClassifier(trainedModel, getFeatures(), beamSize);
            NameFinderEvaluator nerEvaluator = new NameFinderEvaluator(nerClassifier);
            nerEvaluator.evaluate(devSamples);
            double result = nerEvaluator.getFMeasure().getFMeasure();
            double precision = nerEvaluator.getFMeasure().getPrecisionScore();
            double recall = nerEvaluator.getFMeasure().getRecallScore();
            StringBuilder sb = new StringBuilder();
            sb.append("Iterations: ").append(iteration).append(" cutoff: ").append(cuttOff).append(" ")
                    .append("PRF: ").append(precision).append(" ").append(recall).append(" ").append(result)
                    .append("\n");
            Files.append(sb.toString(), new File("ner-results.txt"), Charsets.UTF_8);
            List<Integer> bestParams = new ArrayList<Integer>();
            bestParams.add(iteration);
            bestParams.add(cuttOff);
            results.put(bestParams, result);
            System.out.println();
            System.out.println("Iterations: " + iteration + " cutoff: " + cuttOff);
            System.out.println(nerEvaluator.getFMeasure());
        }
    }
    // print F1 results by iteration
    System.err.println();
    InputOutputUtils.printIterationResults(results);
    InputOutputUtils.getBestIterations(results, allParams);
    finalParams = allParams.get(0);
    System.err.println("Final Params " + finalParams.get(0) + " " + finalParams.get(1));
    return finalParams;
}

From source file:org.deeplearning4j.optimize.listeners.CheckpointListener.java

private static String write(String str, File f) {
    try {/*from  w  ww  .  j  a  v a 2  s.c  o m*/
        if (!f.exists()) {
            f.createNewFile();
        }
        Files.append(str, f, Charset.defaultCharset());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return str;
}

From source file:org.dllearner.kb.dataset.AbstractOWLOntologyDataset.java

private void add403Error(URL url) {
    try {/*from  w ww .jav a  2s. c o  m*/
        Files.append(url.toString() + "\n", new File(directory, "403.txt"), Charset.defaultCharset());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.moe.idea.builder.MOEModuleBuilder.java

private void modifyGradleSettings(@NotNull File file, Module[] modules) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();

    String newLine = System.getProperty("line.separator");

    String existing = Files.toString(file, Charsets.UTF_8);

    if (!existing.endsWith(newLine)) {
        stringBuilder.append(newLine);/*from   w w  w .  jav a2  s. c om*/
    }

    for (Module module : modules) {
        stringBuilder.append("include ':");
        stringBuilder.append(module.getName());
        stringBuilder.append("'");
        stringBuilder.append(newLine);
    }

    Files.append(stringBuilder.toString(), file, Charsets.UTF_8);
}

From source file:ca.ualberta.physics.cssdp.configuration.ComponentProperties.java

public static void dumpToFile(File file) {
    // clear file.
    try {/*  w  w  w.  j  a v  a  2 s.  com*/
        Files.write("".getBytes(), file);
    } catch (IOException e) {
        Throwables.propagate(e);
    }
    Set<String> components = INSTANCES.keySet();
    for (String componentName : components) {
        ComponentProperties properties = ComponentProperties.properties(componentName);
        Set<String> stringPropertyNames = properties.properties.stringPropertyNames();
        List<String> keys = new ArrayList<String>(stringPropertyNames);
        Collections.sort(keys);
        for (String key : keys) {
            try {
                if (key.contains("pass")) {
                    Files.append(componentName + "." + key + "=filtered\n", file, Charset.forName("UTF-8"));
                } else {
                    Files.append(componentName + "." + key + "=" + properties.getString(key) + "\n", file,
                            Charset.forName("UTF-8"));
                }
            } catch (IOException e) {
                Throwables.propagate(e);
            }
        }
    }

}

From source file:org.primefaces.extensions.optimizerplugin.optimizer.ClosureCompilerOptimizer.java

private void writeSourceMappingURL(File minifiedFile, File sourceMapFile, String sourceMapRoot, Charset cset,
        Log log) {//from  w  w w. ja va 2 s. c o m
    try {
        // write sourceMappingURL
        String smRoot = (sourceMapRoot != null ? sourceMapRoot : "");
        Files.append(System.getProperty("line.separator"), minifiedFile, cset);
        Files.append("//# sourceMappingURL=" + smRoot + sourceMapFile.getName(), minifiedFile, cset);
    } catch (IOException e) {
        log.error("//# sourceMappingURL for the minified file " + minifiedFile + " could not be written", e);
    }
}

From source file:org.opencloudb.server.handler.ServerLoadDataInfileHandler.java

private void saveDataToFile(LoadData data, String dnName) {
    if (data.getFileName() == null) {
        String dnPath = tempPath + dnName + ".txt";
        data.setFileName(dnPath);/*www. j a va2 s. c  o m*/
    }

    File dnFile = new File(data.getFileName());
    try {
        Files.append(joinLine(data.getData(), data), dnFile, Charset.forName(loadData.getCharset()));

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        data.setData(null);

    }

}