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:net.chris54721.infinitycubed.workers.PackLoader.java

@Override
public void run() {
    try {/*from  w  ww . jav  a2s  .  c  o m*/
        LogHelper.info("Loading and updating modpacks");
        String publicJson = Utils.toString(new URL(Reference.FILES_URL + "public.json"));
        Type stringIntMap = new TypeToken<LinkedHashMap<String, Integer>>() {
        }.getType();
        LinkedHashMap<String, Integer> publicObjects = Reference.DEFAULT_GSON.fromJson(publicJson,
                stringIntMap);
        File localJson = new File(Resources.getFolder(Reference.PACKS_FOLDER), "public.json");
        List<String> updatePacks = new ArrayList<String>();
        if (localJson.isFile()) {
            String localPublicJson = Files.toString(localJson, Charsets.UTF_8);
            LinkedHashMap<String, Integer> localPublicObjects = Reference.DEFAULT_GSON.fromJson(localPublicJson,
                    stringIntMap);
            for (String pack : publicObjects.keySet()) {
                if (!localPublicObjects.containsKey(pack)
                        || !localPublicObjects.get(pack).equals(publicObjects.get(pack))) {
                    updatePacks.add(pack);
                }
            }
        } else
            updatePacks.addAll(publicObjects.keySet());
        Files.write(publicJson, localJson, Charsets.UTF_8);
        if (updatePacks.size() > 0) {
            for (String pack : updatePacks) {
                LogHelper.info("Updating JSON file for modpack " + pack);
                URL packJsonURL = Resources.getUrl(Resources.ResourceType.PACK_JSON, pack + ".json");
                File packJsonFile = Resources.getFile(Resources.ResourceType.PACK_JSON, pack + ".json");
                if (packJsonFile.isFile())
                    packJsonFile.delete();
                Downloadable packJsonDownloadable = new Downloadable(packJsonURL, packJsonFile);
                if (!packJsonDownloadable.download())
                    LogHelper.error("Failed updating JSON for modpack " + pack);
            }
        }
        Collection<File> packJsons = FileUtils.listFiles(Resources.getFolder(Reference.DATA_FOLDER),
                new String[] { "json" }, false);
        for (File packJsonFile : packJsons)
            loadPack(FilenameUtils.getBaseName(packJsonFile.getName()));
    } catch (Exception e) {
        LogHelper.fatal("Failed updating and loading public packs", e);
    }
}

From source file:hu.petabyte.redflags.engine.scope.AutoScope.java

private void save(NoticeID id) {
    try {/*ww  w .j  a  v  a2s .c om*/
        Files.write(id.toString(), new File(FILENAME), Charsets.UTF_8);
    } catch (IOException e) {
        LOG.warn("Failed to save notice id: {}", e.getMessage());
        LOG.trace("Failed to save notice id", e);
    }
}

From source file:org.glowroot.agent.dist.PluginJsonTransformer.java

private void createArtifactJar(Set<Artifact> artifacts) throws Exception {
    List<PluginDescriptor> pluginDescriptors = getPluginDescriptors(artifacts);
    validateConfigForDuplicates();//from www  . j  a v  a  2  s  . c o  m
    for (PluginConfig pluginConfig : pluginConfigs) {
        validateConfigItem(pluginDescriptors, pluginConfig);
    }
    String pluginsJson = transform(pluginDescriptors);
    File metaInfDir = new File(project.getBuild().getOutputDirectory(), "META-INF");
    File file = new File(metaInfDir, "glowroot.plugins.json");
    if (!metaInfDir.exists() && !metaInfDir.mkdirs()) {
        throw new IOException("Could not create directory: " + metaInfDir.getAbsolutePath());
    }
    Files.write(pluginsJson, file, UTF_8);
}

From source file:pl.asie.foamfix.coremod.FoamFixCore.java

public void injectData(final Map<String, Object> data) {
    FoamFixShared.coremodEnabled = true;
    FoamFixShared.config.init(new File(new File("config"), "foamfix.cfg"), true);

    if (FoamFixShared.config.clInitOptions) {
        try {/*from w w w . j ava2 s .  c  o m*/
            File optionsFile = new File("options.txt");
            if (!optionsFile.exists()) {
                Files.write("mipmapLevels:0\n", optionsFile, Charsets.UTF_8);
            }
            File forgeCfgFile = new File(new File("config"), "forge.cfg");
            if (!forgeCfgFile.exists()) {
                Files.write("client {\nB:alwaysSetupTerrainOffThread=true\n}\n", forgeCfgFile, Charsets.UTF_8);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if (FoamFixShared.config.geBlacklistLibraryTransformers) {
        LaunchClassLoader classLoader = (LaunchClassLoader) getClass().getClassLoader();
        classLoader.addTransformerExclusion("com.ibm.icu.");
        classLoader.addTransformerExclusion("com.sun.");
        classLoader.addTransformerExclusion("gnu.trove.");
        classLoader.addTransformerExclusion("io.netty.");
        classLoader.addTransformerExclusion("it.unimi.dsi.fastutil.");
        classLoader.addTransformerExclusion("joptsimple.");
        classLoader.addTransformerExclusion("org.apache.");
        classLoader.addTransformerExclusion("oshi.");
        classLoader.addTransformerExclusion("scala.");
    }

    LaunchClassLoader classLoader = (LaunchClassLoader) getClass().getClassLoader();

    // Not so simple!
    try {
        Field transformersField = ReflectionHelper.findField(LaunchClassLoader.class, "transformers");
        List<IClassTransformer> transformerList = (List<IClassTransformer>) transformersField.get(classLoader);

        for (int i = 0; i < transformerList.size(); i++) {
            IClassTransformer transformer = transformerList.get(i);
            IClassTransformer parentTransformer = transformer;
            if (transformer instanceof ASMTransformerWrapper.TransformerWrapper) {
                Field parentTransformerField = ReflectionHelper
                        .findField(ASMTransformerWrapper.TransformerWrapper.class, "parent");
                parentTransformer = (IClassTransformer) parentTransformerField.get(transformer);
            }
            /*
                            if (parentTransformer instanceof SideTransformer) {
            if (FoamFixShared.config.geFasterSideTransformer) {
                transformerList.set(i, new FoamySideTransformer());
            }
                            }
                            */
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    FoamFixTransformer.init();
}

From source file:org.eclipse.wst.jsdt.angularjs.core.api.AngularJsProject.java

/**
 * Creates the project on the file system.
 *///from  w  w w .  ja v  a  2 s . co  m
public void create() {
    Map<String, CharSequence> path2content = new HashMap<String, CharSequence>();
    path2content.putAll(this.getAppContents());
    path2content.putAll(this.createTests());
    path2content.putAll(this.createExtras());

    Set<Entry<String, CharSequence>> entries = path2content.entrySet();
    for (Entry<String, CharSequence> entry : entries) {
        try {
            Files.write(entry.getValue(), new File(directory, entry.getKey()), Charset.forName(UTF8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.android.build.gradle.tasks.factory.IncrementalSafeguard.java

/**
 * Incremental task will only execute when any of the generated files (in particular R.java)
 * has changed.//  www  . ja v a  2 s.  c om
 *
 * @param inputs the incremental changes as provided by Gradle.
 * @throws IOException if something went wrong cleaning up the javac compilation output.
 */
@TaskAction
protected void execute(IncrementalTaskInputs inputs) throws IOException {
    getLogger().debug("Removing old bits to force javac non incremental mode.");
    File outputFile = new File(generatedOutputDir, "tag.txt");
    Files.createParentDirs(outputFile);
    Files.write("incremental task execution", outputFile, Charsets.UTF_8);
    // since we execute, force the recompilation of all the user's classes.
    try {
        FileUtils.deletePath(javaOutputDir);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.shmsoft.dmass.review.HiveAnalyzer.java

public void loadAndDisplay() throws IOException {
    // read the first line of the load file
    String headerStr = Files.readFirstLine(new File(resultFileName), Charset.defaultCharset());
    String delimName = Project.getProject().getFieldSeparator();
    char delim = Delim.getDelim(delimName);
    String[] headers = headerStr.split(String.valueOf(delim));
    StringBuilder createScript = new StringBuilder();
    String tableName = "load_file";
    createScript.append("DROP TABLE IF EXISTS " + tableName + ";" + "\n");
    createScript.append("create table " + tableName + " (");
    for (String header : headers) {
        header = header.trim();//w w w  .  j a v a2s . c  om
        header = header.replaceAll(" ", "_");
        if ("TO".equalsIgnoreCase(header))
            header = "Email_" + header;
        if ("FROM".equalsIgnoreCase(header))
            header = "Email_" + header;
        if ("CC".equalsIgnoreCase(header))
            header = "Email_" + header;
        if ("BCC".equalsIgnoreCase(header))
            header = "Email_" + header;
        if (!header.isEmpty()) {
            createScript.append(header + " string,");
        } else {
            createScript.append("no_value" + " string,");
        }
    }
    createScript.replace(createScript.length() - 1, createScript.length(), ")");
    createScript.append("\n");
    createScript.append("row format delimited\n");
    createScript.append("fields terminated by '" + Delim.getSpelledDelim(delimName) + "'\n");
    createScript.append("stored as textfile");
    String scriptFile = TMP + "hive_create_table.sql";
    Files.write(createScript.toString(), new File(scriptFile), Charset.defaultCharset());
    String cmd = "hive -f " + scriptFile;
    PlatformUtil.runUnixCommand(cmd);

    StringBuilder loadScript = new StringBuilder();
    loadScript.append("load data local inpath '" + resultFileName + "'\n");
    loadScript.append("overwrite into table " + tableName + ";");

    String loadFile = TMP + "hive_load_table.sql";
    Files.write(loadScript.toString(), new File(loadFile), Charset.defaultCharset());
    cmd = "hive -f " + loadFile;
    PlatformUtil.runUnixCommand(cmd);
    cmd = "xterm -e hive";
    PlatformUtil.runUnixCommand(cmd);
}

From source file:co.mitro.keyczar.RoundTripper.java

private static void sign(String keyPath, String message, String outpath) throws KeyczarException, IOException {
    Signer key = new Signer(Util.readJsonFromPath(keyPath));
    System.out.println("signing message length " + message.length());
    String output = key.sign(message);

    Files.write(output, new File(outpath), Charsets.UTF_8);
}

From source file:me.lucko.luckperms.sponge.service.persisted.SubjectStorage.java

public void saveToFile(PersistedSubject subject, File file) throws IOException {
    file.getParentFile().mkdirs();//from  www  .  j  a  v  a 2s. c om
    if (file.exists()) {
        file.delete();
    }
    file.createNewFile();

    Files.write(saveToString(new SubjectDataHolder(subject.getSubjectData())), file, Charset.defaultCharset());
}

From source file:com.facebook.buck.parcelable.GenParcelableRule.java

@Override
protected List<Step> buildInternal(BuildContext context) throws IOException {
    Step step = new Step() {

        @Override/*w w w .  j  av a  2s .  co  m*/
        public int execute(ExecutionContext context) {
            for (String src : srcs) {
                try {
                    // Generate the Java code for the Parcelable class.
                    ParcelableClass parcelableClass = Parser.parse(new File(src));
                    String generatedJava = new Generator(parcelableClass).generate();

                    // Write the generated Java code to a file.
                    File outputPath = new File(getOutputPathForParcelableClass(parcelableClass));
                    Files.createParentDirs(outputPath);
                    Files.write(generatedJava, outputPath, Charsets.UTF_8);
                } catch (IOException e) {
                    e.printStackTrace(context.getStdErr());
                    return 1;
                }
            }
            return 0;
        }

        @Override
        public String getShortName(ExecutionContext context) {
            return "gen_parcelable";
        }

        @Override
        public String getDescription(ExecutionContext context) {
            return "gen_parcelable";
        }
    };

    return ImmutableList.of(step);
}