List of usage examples for com.google.common.io Files write
public static void write(CharSequence from, File to, Charset charset) throws IOException
From source file:org.jboss.maven.plugins.qstools.fixers.ReadmeMetadataFixer.java
/** * @param groupId/*from w ww. ja v a 2 s . c o m*/ * @param readme * @throws IOException */ private void fixReadmeFile(String groupId, File readme) throws IOException { BufferedReader br = new BufferedReader(new FileReader(readme)); try { Pattern p = Pattern.compile(regexPattern); StringBuilder sb = new StringBuilder(); boolean readmeModified = false; while (br.ready()) { String line = br.readLine(); Matcher m = p.matcher(line); if (m.find()) { // Only get metadata lines if (!line.matches("\\w.*\\s\\s")) { // if line doesn't have two spaces line = line.replace(line.trim(), line + " "); // add two spaces only on a trimmed line readmeModified = true; } } sb.append(line + "\n"); } if (readmeModified) { Files.write(sb.toString(), readme, Charset.forName("UTF-8")); getLog().info("Saving changes to " + readme); } } finally { if (br != null) { br.close(); } } }
From source file:com.google.devtools.j2objc.gen.SourceFileGenerator.java
protected void save(String path) { try {// w ww . ja va 2 s.c om File outputFile = new File(outputDirectory, path); File dir = outputFile.getParentFile(); if (dir != null && !dir.exists()) { if (!dir.mkdirs()) { ErrorUtil.warning("cannot create output directory: " + outputDirectory); } } String source = builder.toString(); // Make sure file ends with a new-line. if (!source.endsWith("\n")) { source += '\n'; } Files.write(source, outputFile, Options.getCharset()); } catch (IOException e) { ErrorUtil.error(e.getMessage()); } finally { reset(); } }
From source file:eu.numberfour.n4js.antlr.compressor.ParserCompressorFragment2.java
@Override public void generate() { for (String fileName : grammarFiles) { File file = new File(fileName); String javaSource = null; try {//from ww w .j a v a 2s.c o m javaSource = Files.toString(file, Charsets.UTF_8); } catch (Exception ex) { LOGGER.error("Error reading file " + fileName + ": " + ex.getMessage()); } if (javaSource != null) { String compressed = process(javaSource, file); LOGGER.info("File " + readableFileName(file) + " compressed: " + javaSource.length() + " --> " + compressed.length() + " (" + 100 * compressed.length() / javaSource.length() + "%)"); if (backup) { try { Files.copy(file, new File(file.getParentFile(), file.getName() + ".bak")); } catch (IOException e) { LOGGER.error("Error creating backup of " + readableFileName(file) + ": " + e.getMessage()); return; } } try { Files.write(compressed, file, Charsets.UTF_8); } catch (IOException e) { LOGGER.error("Error writing compressed file " + readableFileName(file) + ": " + e.getMessage()); } } } }
From source file:org.jfrog.build.extractor.release.PropertiesTransformer.java
/** * {@inheritDoc}/* www. j a v a2s . c om*/ * * @return True in case the properties file was modified during the transformation. False otherwise. */ public Boolean transform() throws IOException, InterruptedException { if (!propertiesFile.exists()) { throw new IllegalArgumentException( "Couldn't find properties file: " + propertiesFile.getAbsolutePath()); } Properties properties = new Properties(); EolDetectingInputStream eolDetectingInputStream = null; try { eolDetectingInputStream = new EolDetectingInputStream(new FileInputStream(propertiesFile)); properties.load(eolDetectingInputStream); } finally { IOUtils.closeQuietly(eolDetectingInputStream); } String eol = eolDetectingInputStream.getEol(); boolean hasEol = !"".equals(eol); StringBuilder resultBuilder = new StringBuilder(); boolean modified = false; Enumeration<?> propertyNames = properties.propertyNames(); while (propertyNames.hasMoreElements()) { String propertyName = (String) propertyNames.nextElement(); String propertyValue = properties.getProperty(propertyName); StringBuilder lineBuilder = new StringBuilder(propertyName).append("="); String newPropertyValue = versionsByName.get(propertyName); if ((newPropertyValue != null) && !newPropertyValue.equals(propertyValue)) { if (!modified) { modified = true; } lineBuilder.append(newPropertyValue); } else { lineBuilder.append(propertyValue); } resultBuilder.append(lineBuilder.toString()); if (hasEol) { resultBuilder.append(eol); } } if (modified) { propertiesFile.delete(); String toWrite = resultBuilder.toString(); Files.write(toWrite, propertiesFile, Charsets.UTF_8); } return modified; }
From source file:eu.numberfour.n4js.antlr.compressor.ParserCompressorFragment.java
@Override public void generate(org.eclipse.xtext.Grammar grammar, org.eclipse.xpand2.XpandExecutionContext ctx) { for (String fileName : grammarFiles) { File file = new File(fileName); String javaSource = null; try {// w w w . ja v a 2s .com javaSource = Files.toString(file, Charsets.UTF_8); } catch (Exception ex) { log.error("Error reading file " + fileName + ": " + ex.getMessage()); } if (javaSource != null) { String compressed = process(javaSource, file); log.info("File " + readableFileName(file) + " compressed: " + javaSource.length() + " --> " + compressed.length() + " (" + 100 * compressed.length() / javaSource.length() + "%)"); if (backup) { try { Files.copy(file, new File(file.getParentFile(), file.getName() + ".bak")); } catch (IOException e) { log.error("Error creating backup of " + readableFileName(file) + ": " + e.getMessage()); return; } } try { Files.write(compressed, file, Charsets.UTF_8); } catch (IOException e) { log.error("Error writing compressed file " + readableFileName(file) + ": " + e.getMessage()); } } } }
From source file:com.google.devtools.j2objc.DeadCodeProcessor.java
@Override protected void processUnit(String path, String source, CompilationUnit unit, TimeTracker ticker) { logger.finest("removing dead code: " + path); String newSource = rewriteSource(source, unit, deadCodeMap, ticker); if (!newSource.equals(source)) { // Save the new source to the tmpdir and update the files list. File outFile = new File(tempDir, getRelativePath(path, unit)); try {/*from ww w .j a va2 s .co m*/ Files.write(newSource, outFile, Options.getCharset()); } catch (IOException e) { ErrorUtil.error(e.getMessage()); } path = outFile.getAbsolutePath(); ticker.tick("Print new source to file"); } resultSources.add(path); }
From source file:com.github.rinde.dynurg.PoissonDynamismExperiment.java
static void createDynamismHistogram(TimeSeriesGenerator generator, long seed, File file, int repetitions) { try {/* w w w . j a v a 2 s.com*/ Files.createParentDirs(file); } catch (final IOException e1) { throw new IllegalStateException(e1); } final RandomGenerator rng = new MersenneTwister(seed); final List<Double> values = newArrayList(); final SummaryStatistics ss = new SummaryStatistics(); for (int i = 0; i < repetitions; i++) { final List<Double> times = generator.generate(rng.nextLong()); ss.addValue(times.size()); final double dynamism = Metrics.measureDynamism(times, LENGTH_OF_DAY); values.add(dynamism); } System.out.println( file.getName() + " has #events: mean: " + ss.getMean() + " +- " + ss.getStandardDeviation()); final StringBuilder sb = new StringBuilder(); sb.append(Joiner.on("\n").join(values)); try { Files.write(sb.toString(), file, Charsets.UTF_8); } catch (final IOException e) { throw new IllegalStateException(e); } }
From source file:org.jetbrains.kotlin.maven.K2JSCompilerMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { super.execute(); if (appendLibraryJS != null && appendLibraryJS.booleanValue()) { try {//from w w w .j a v a 2 s .c o m Charset charset = Charset.defaultCharset(); File file = new File(outputFile); String text = Files.toString(file, charset); StringBuilder builder = new StringBuilder(); appendFile(KOTLIN_JS_LIB_ECMA3, builder); appendFile(KOTLIN_JS_LIB, builder); appendFile(KOTLIN_JS_MAPS, builder); builder.append("\n"); builder.append(text); Files.write(builder.toString(), file, charset); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } if (copyLibraryJS != null && copyLibraryJS.booleanValue()) { getLog().info("Copying kotlin JS library to " + outputKotlinJSDir); copyJsLibraryFile(KOTLIN_JS_MAPS); copyJsLibraryFile(KOTLIN_JS_LIB); copyJsLibraryFile(KOTLIN_JS_LIB_ECMA3); copyJsLibraryFile(KOTLIN_JS_LIB_ECMA5); } }
From source file:com.eucalyptus.cassandra.config.CassandraSysUtil.java
static void writeConfiguration() throws IOException { Files.write(generateCassandraYaml(), BaseDirectory.VAR.getChildFile("cassandra", "conf", "cassandra.yaml"), StandardCharsets.UTF_8); Files.write(generateCassandraRackDcProperties(), BaseDirectory.VAR.getChildFile("cassandra", "conf", "cassandra-rackdc.properties"), StandardCharsets.UTF_8); }
From source file:org.sonar.plugins.python.flake8.Flake8IssuesAnalyzer.java
public List<Issue> analyze(String path, Charset charset, File out) throws IOException { Command command = Command.create(flake8).addArgument(path); if (flake8ConfigParam != null) { command.addArgument(flake8ConfigParam); }//w w w. j a v a2 s .c o m LOG.debug("Calling command: '{}'", command.toString()); long timeoutMS = 300000; // =5min CommandStreamConsumer stdOut = new CommandStreamConsumer(); CommandStreamConsumer stdErr = new CommandStreamConsumer(); CommandExecutor.create().execute(command, stdOut, stdErr, timeoutMS); // the error stream can contain a line like 'no custom config found, using default' // any bigger output on the error stream is likely a flake8 malfunction if (stdErr.getData().size() > 1) { LOG.warn("Output on the error channel detected: this is probably due to a problem on flake8's side."); LOG.warn("Content of the error stream: \n\"{}\"", StringUtils.join(stdErr.getData(), "\n")); } Files.write(StringUtils.join(stdOut.getData(), "\n"), out, charset); return parseOutput(stdOut.getData()); }