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

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

Introduction

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

Prototype

public static String toString(File file, Charset charset) throws IOException 

Source Link

Usage

From source file:scoutdoc.main.converter.PagesTemplateProvider.java

@Override
public Template resolveTemplate(String templateName) {
    if (Strings.isNullOrEmpty(templateName)) {
        return null;
    }/*from  w  w  w .jav a2s  .co  m*/
    String basicName = templateName.toLowerCase().startsWith("template:")
            ? templateName.substring(templateName.lastIndexOf(':') + 1)
            : templateName;

    String templatePageName = "Template:" + basicName.substring(0, 1).toUpperCase() + basicName.substring(1);
    Page templatePage = Pages.get(templatePageName);
    File file = PageUtility.toContentFile(templatePage);

    if (file.exists()) {
        try {
            String content = Files.toString(file, Charsets.UTF_8);

            Template template = new Template();
            template.setName(basicName);
            template.setTemplateMarkup(content);
            return template;

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.android.ide.common.blame.parser.aapt.ReadOnlyDocument.java

/**
 * Creates a new {@link ReadOnlyDocument} for the given file.
 *
 * @param file the file whose text will be stored in the document. UTF-8 charset is used to
 *             decode the contents of the file.
 * @throws java.io.IOException if an error occurs while reading the file.
 *//*from w  w w  .j av  a2 s.  c o m*/
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
ReadOnlyDocument(@NonNull File file) throws IOException {
    String xml = Files.toString(file, Charsets.UTF_8);
    if (xml.startsWith("\uFEFF")) { // Strip byte order mark if necessary
        xml = xml.substring(1);
    }
    mFileContents = xml;
    myFile = file;
    myLastModified = file.lastModified();
    myOffsets = Lists.newArrayListWithExpectedSize(mFileContents.length() / 30);
    for (int i = 0; i < mFileContents.length(); i++) {
        char c = mFileContents.charAt(i);
        if (c == '\n') {
            myOffsets.add(i + 1);
        }
    }
}

From source file:org.jboss.maven.plugins.qstools.fixers.XMLTabFixer.java

@Override
public void fixProject(MavenProject project, Document doc) throws Exception {
    List<File> xmlFiles = FileUtils.getFiles(project.getBasedir(), "**/*.xml", "");
    for (File xmlSource : xmlFiles) {
        getLog().debug("Fixing tab on " + xmlSource);
        String source = Files.toString(xmlSource, Charset.forName("UTF-8"));
        String replaced = source.replace("\t", "    ");
        Files.write(replaced, xmlSource, Charset.forName("UTF-8"));
    }//  ww  w .  java  2 s.  c o m

}

From source file:com.google.devtools.build.lib.actions.LocalHostResourceManagerLinux.java

private static String readContent(String filename) throws IOException {
    return Files.toString(new File(filename), Charset.defaultCharset());
}

From source file:org.opendaylight.controller.config.yang.test.plugin.ProcessSources.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (directory == null || !directory.exists()) {
        super.getLog().error("Directory does not exists.");
    }/*  w ww .  j  a  v  a  2  s . c  o m*/
    File sourceDirectory = new File(
            directory.getPath() + Util.replaceDots(".org.opendaylight.controller.config.yang.test.impl"));
    if (!sourceDirectory.exists()) {
        super.getLog().error(String.format("Source directory does not exists %s", sourceDirectory.getPath()));
    }

    File[] sourceFiles = sourceDirectory.listFiles();
    for (File sourceFile : sourceFiles) {
        if (sourceFile.getName().endsWith(".java")) {
            String sourceContent;
            try {
                sourceContent = Files.toString(sourceFile, StandardCharsets.UTF_8);
            } catch (IOException e) {
                getLog().error(String.format("Cannot read %s", sourceFile.getAbsolutePath()), e);
                continue;
            }
            if (sourceFile.getName().endsWith("Module.java")
                    || sourceFile.getName().endsWith("ModuleFactory.java")) {
                File stubFile = new File(sourceFile.getPath().replace(".java", "Stub.txt"));
                if (stubFile.exists()) {
                    String stubContent = null;
                    try {
                        stubContent = Files.toString(stubFile, StandardCharsets.UTF_8);
                    } catch (IOException e) {
                        getLog().error(String.format("Cannot read %s", stubFile.getAbsolutePath()), e);
                    }
                    if (stubContent != null) {
                        sourceContent = rewriteStub(sourceContent, stubContent);
                    }
                }
            }
            // remove copyright headers as they can contain timestamp
            sourceContent = removeCopyrights(sourceContent);

            // replace the file content
            try {
                Files.write(sourceContent, sourceFile, StandardCharsets.UTF_8);
            } catch (IOException e) {
                getLog().error(String.format("Cannot write %s", sourceFile.getAbsolutePath()), e);
            }
        }

    }
}

From source file:net.chris54721.infinitycubed.workers.AccountLoader.java

@Override
public void run() {
    try {/*from   www  . j  a v a2  s.c  om*/
        LogHelper.info("Loading saved accounts");
        Collection<File> accountJsons = FileUtils.listFiles(Resources.getFolder(Reference.ACCOUNTS_FOLDER),
                new String[] { "json" }, false);
        Type stringMap = new TypeToken<LinkedHashMap<String, String>>() {
        }.getType();
        for (File accountJson : accountJsons) {
            Map<String, String> data = Reference.DEFAULT_GSON
                    .fromJson(Files.toString(accountJson, Charsets.UTF_8), stringMap);
            if (data == null)
                throw new NullPointerException(
                        "Content of file " + accountJson.getName() + " deserializes to null");
            Account account = new Account(data.get("uuid"), data.get("username"), data.get("nickname"),
                    data.get("accessToken"), data.get("clientToken"));
            boolean selected = Launcher.getSettings().getProperty("selectedAccount")
                    .equalsIgnoreCase(data.get("uuid"));
            account.fetchSkin(selected);
            Launcher.accounts.add(account);
            if (selected)
                selectAccount(account);
        }
    } catch (Exception e) {
        LogHelper.fatal("Failed loading accounts", e);
    }
}

From source file:org.jvnet.hudson.plugins.periodicbackup.BackupObject.java

/**
 *
 * @return transformation function to convert BackupObject file into BackupObject
 *//*from  ww w .  java  2s . c  o m*/
public static Function<File, BackupObject> getFromFile() {
    return new Function<File, BackupObject>() {
        public BackupObject apply(File file) {
            if (file != null) {
                try {
                    return (BackupObject) Hudson.XSTREAM
                            .fromXML(Files.toString(file, Charset.defaultCharset()));
                } catch (IOException e) {
                    return null;
                }
            } else {
                return null;
            }
        }
    };
}

From source file:datamine.mojo.storage.TableInterfaceConvertorGenerationMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    validateArguments();/*from   ww  w.j  a  va2s . co m*/

    InterfaceConvertorGenerator generator = new InterfaceConvertorGenerator(outputDirectory.getAbsolutePath(),
            packageName, interfacePackageName);

    try {
        // generate the java source codes
        Schema schema = new JsonSchemaConvertor().apply(Files.toString(schemaPath, Charsets.UTF_8));
        schema.accept(generator);
        generator.generate();
    } catch (IOException e) {
        throw new MojoExecutionException("Error generating Java interfaces for table conversion!", e);
    }
}

From source file:org.pantsbuild.args4j.ArgfileOptionHandler.java

@Override
public int parseArguments(final Parameters params) throws CmdLineException {
    return delegate.parseArguments(new Parameters() {
        @Override/*from w  w w.j  a v  a2s.c o m*/
        public String getParameter(int idx) throws CmdLineException {
            String value = params.getParameter(idx);
            if (!value.startsWith("@")) {
                return value;
            }

            try {
                return Files.toString(new File(value.substring(1)), Charsets.UTF_8).trim();
            } catch (IOException e) {
                throw new InvalidCmdLineArgumentException(delegate.option, value,
                        String.format("Failed to read argfile: %s", e.getMessage()));
            }
        }

        @Override
        public int size() {
            return params.size();
        }
    });
}

From source file:datamine.mojo.storage.recordbuffers.RecordBuffersTestTableGenerationMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    validateArguments();//w ww.  j  a v  a 2s. com

    try {
        //0. generate the java source codes
        Schema schema = new JsonSchemaConvertor().apply(Files.toString(schemaPath, Charsets.UTF_8));

        //1. generate codes for table unit testing
        TableTestDataGenerator gen2 = new TableTestDataGenerator(testOutputDirectory.getAbsolutePath(),
                packageName, metadataPackageName, interfacePackageName);
        gen2.apply(schema);

    } catch (IOException e) {
        throw new MojoExecutionException("Error generating Java classes for table testing!", e);
    }
}