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:com.android.build.gradle.integration.common.fixture.TemporaryProjectModification.java

public void modifyFile(@NonNull String relativePath, @NonNull Function<String, String> modification)
        throws InitializationError {
    File file = mTestProject.file(relativePath);

    String currentContent = null;
    try {/*  ww w .  ja v  a  2  s .  c  om*/
        currentContent = Files.toString(file, Charsets.UTF_8);
    } catch (IOException e) {
        throw new InitializationError(e);
    }

    // We can modify multiple times, but we only want to store the original.
    if (!mFileContentToRestore.containsKey(relativePath)) {
        mFileContentToRestore.put(relativePath, currentContent);
    }

    String newContent = modification.apply(currentContent);

    if (newContent == null) {
        assertTrue("File should have been deleted", file.delete());
    } else {
        try {
            Files.write(newContent, file, Charsets.UTF_8);
        } catch (IOException e) {
            throw new InitializationError(e);
        }
    }
}

From source file:org.sonar.plugins.xml.checks.XmlFile.java

/**
 * Create a temporary file without any character before the prolog and update the following
 * attributes in order to correctly report issues:
 * <ul>/*from w ww.j  av  a2 s . c  o m*/
 *   <li> lineDeltaForIssue
 *   <li> file
 */
private void processCharBeforePrologInFile(FileSystem fileSystem, int lineDelta) {
    try {
        String content = Files.toString(inputFile.file(), fileSystem.encoding());
        File tempFile = new File(fileSystem.workDir(), inputFile.file().getName());

        int index = content.indexOf(XML_PROLOG_START_TAG);
        Files.write(content.substring(index), tempFile, fileSystem.encoding());

        noCharBeforePrologFile = tempFile;

        if (index != -1) {
            characterDeltaForHighlight += index;
        }

        if (lineDelta > 1) {
            lineDeltaForIssue = lineDelta - 1;
        }

    } catch (IOException e) {
        LOG.warn("Unable to analyse file {}", inputFile.absolutePath(), e);
    }
}

From source file:net.minecraftforge.fml.relauncher.libraries.SnapshotJson.java

public void write(File target) throws IOException {
    Files.write(GSON.toJson(this), target, StandardCharsets.UTF_8);
}

From source file:com.facebook.buck.android.GenRDotJavaStep.java

/**
 * Creates a command that will run {@code aapt} for the purpose of generating {@code R.java}.
 * Additionally, this command will generate the corresponding {@code R.txt} file.
 * @param resDirectories Directories of resource files. Will be specified with {@code -S} to
 *     {@code aapt}//from   w  w w  .j a v a2  s  .  c o m
 * @param genDirectoryPath Directory where {@code R.java} and potentially {@code R.txt} will be
 *     generated
 * @param libraryPackage Normally, {@code aapt} expects an {@code AndroidManifest.xml} so that it
 *     can extract the {@code package} attribute to determine the Java package of the generated
 *     {@code R.java} file. For this class, the client must specify the {@code package} directly
 *     rather than the path to {@code AndroidManifest.xml}. This precludes the need to keep a
 *     number of dummy {@code AndroidManifest.xml} files in the codebase.
 * @param isTempRDotJava If true, the values of the resource values in the generated
 *     {@code R.java} will be meaningless.
 *     <p>
 *     If false, this command will produce an {@code R.java} file with resource values designed to
 *     match those in an .apk that includes the resources.
 * @param extraLibraryPackages
 */
public GenRDotJavaStep(Set<Path> resDirectories, Path genDirectoryPath, String libraryPackage,
        boolean isTempRDotJava, Set<String> extraLibraryPackages) {
    this.resDirectories = ImmutableSet.copyOf(resDirectories);

    File tmpDir = Files.createTempDir();
    tmpDir.deleteOnExit();

    // TODO(mbolin): This command is run fairly frequently, often for the same value of
    // libraryPackage, so consider generating these under buck-out/android, parameterized by
    // libraryPackage, so that AndroidManifest.xml is only written once per package. However, one
    // must be careful when doing this when --num-threads is greater than 1.
    // Another option is to require clients to provide an AndroidManifest.xml for each
    // android_resource() rule in the codebase. This may turn out to be helpful when running the
    // Android linter because then the user will specify the min/max values of Android for a
    // library.
    this.androidManifest = new File(tmpDir, "AndroidManifest.xml");
    try {
        String xml = String.format(
                "<manifest xmlns:android='http://schemas.android.com/apk/res/android' package='%s' />",
                libraryPackage);
        Files.write(xml, androidManifest, Charsets.UTF_8);
    } catch (IOException e) {
        Throwables.propagate(e);
    }

    this.genDirectoryPath = Preconditions.checkNotNull(genDirectoryPath);
    this.isTempRDotJava = isTempRDotJava;
    this.extraLibraryPackages = ImmutableSet.copyOf(extraLibraryPackages);
}

From source file:org.jclouds.examples.rackspace.cloudfiles.CloudFilesPublish.java

/**
 * This method will put a plain text object into the container.
 *//* w w  w. j  a  v  a2s  .  c o m*/
private void createObjectFromFile() throws IOException {
    System.out.format("Create Object From File%n");

    File tempFile = File.createTempFile(FILENAME, SUFFIX);

    try {
        Files.write("Hello Cloud Files", tempFile, Charsets.UTF_8);

        ObjectApi objectApi = cloudFiles.getObjectApi(REGION, CONTAINER_PUBLISH);

        ByteSource byteSource = Files.asByteSource(tempFile);
        Payload payload = Payloads.newByteSourcePayload(byteSource);

        objectApi.put(FILENAME + SUFFIX, payload);
    } finally {
        tempFile.delete();
    }
}

From source file:fr.ens.transcriptome.aozan.util.XMLUtilsWriter.java

/**
 * Create a xml file from document xml./*from  w w  w  .j  av a 2 s  .  co  m*/
 * @param doc document xml
 * @param output the output
 * @throws IOException if an error occurs while writing the file
 * @throws AozanException if document or output file doesn't exist or if an
 *           error occurs during transforming document.
 */
public static void createXMLFile(final Document doc, final File output) throws IOException, AozanException {

    if (doc == null) {
        throw new AozanException("Error create XML file, document doesn't exist.");
    }

    if (output == null) {
        throw new AozanException("Error create XML file, output file is not define.");
    }

    // Transform document XML
    final String text = createXMLFile(doc);

    // Create XML file
    if (output.getAbsolutePath().endsWith(".html")) {
        Files.write(text, new File(output.getAbsolutePath().replace(".html", ".xml")), StandardCharsets.UTF_8);
    } else {
        Files.write(text, output, StandardCharsets.UTF_8);
    }
}

From source file:com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewList.java

private void save(File file) throws IOException {
    //Document document = DomUtilities.createEmptyPlainDocument();
    Document document = DomUtilities.createEmptyDocument();
    if (document != null) {
        for (ConfigurationDescription description : mList) {
            description.toXml(document);
        }//from   ww w.  j av  a  2s .  c o m
        String xml = XmlPrettyPrinter.prettyPrint(document);
        Files.write(xml, file, Charsets.UTF_8);
    }
}

From source file:org.spongepowered.asm.mixin.transformer.debug.RuntimeDecompiler.java

@Override
public void saveClassFile(String path, String qualifiedName, String entryName, String content, int[] mapping) {
    File file = new File(this.outputPath, qualifiedName + ".java");
    file.getParentFile().mkdirs();//from  w  w w .j  av a2s  .c  o  m
    try {
        this.logger.info("Writing {}", file.getAbsolutePath());
        Files.write(content, file, Charsets.UTF_8);
    } catch (IOException ex) {
        this.writeMessage("Cannot write source file " + file, ex);
    }
}

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

/**
 * Retrieves the marker./*from ww  w.j  a va2s .  c om*/
 * 
 * @param found
 *            The id found.
 * @return The marker.
 * @throws IOException
 *             In case of issues
 */
private String retrieveMarker(String found) throws IOException {
    IPath path = Platform.getStateLocation(UsageActivator.getDefault().getBundle());
    if (path != null) {
        path = path.append("hostname"); //$NON-NLS-1$
        if (!path.toFile().exists()) {
            Files.write(found, path.toFile(), Charset.forName("UTF-8")); //$NON-NLS-1$
        } else {
            if (path.toFile().canRead()) {
                return Files.readFirstLine(path.toFile(), Charset.forName("UTF-8")); //$NON-NLS-1$
            }
        }
    }
    return found;
}

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

public void analyze(SparqlEndpointKS ks) {
    Set<Node> existentialMeaninglessProperties = new TreeSet<>(new NodeComparator());

    StringBuilder sb = new StringBuilder();

    // for each class
    //      String query = "SELECT ?cls WHERE {[] a ?cls .}";

    // check data properties
    String query = "SELECT DISTINCT ?p WHERE {?s ?p ?o .}";

    QueryExecution qe = ks.getQueryExecutionFactory().createQueryExecution(query);
    ResultSet rs = qe.execSelect();
    while (rs.hasNext()) {
        QuerySolution qs = rs.next();//from   w  ww  .j a v  a  2s . c o m

        Resource property = qs.getResource("p");
        Resource range = qs.getResource("range");

        //         if(range.equals(XSD.xdouble)) {
        existentialMeaninglessProperties.add(property.asNode());
        //         }
    }
    qe.close();
    for (Node p : existentialMeaninglessProperties) {
        sb.append(p).append("\n");
    }
    existentialMeaninglessProperties.clear();
    sb.append("\n\n");

    // check object properties
    query = "SELECT ?p WHERE {?p a owl:ObjectProperty .}";

    qe = ks.getQueryExecutionFactory().createQueryExecution(query);
    rs = qe.execSelect();
    while (rs.hasNext()) {
        QuerySolution qs = rs.next();

        Resource property = qs.getResource("p");
        existentialMeaninglessProperties.add(property.asNode());

    }
    qe.close();

    for (Node p : existentialMeaninglessProperties) {
        sb.append(p).append("\n");
    }
    try {
        Files.write(sb.toString(), new File(this.getClass().getClassLoader().getResource(PATH).toURI()),
                Charsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}