Example usage for java.io FileWriter close

List of usage examples for java.io FileWriter close

Introduction

In this page you can find the example usage for java.io FileWriter close.

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.grillecube.engine.renderer.model.json.JSONHelper.java

public static void writeJSONObjectToFile(File file, JSONObject json) {
    try {/*w  w  w .j  a  va2  s .  co m*/
        FileWriter writer = new FileWriter(file);
        writer.write(json.toString());
        writer.flush();
        writer.close();
    } catch (Exception e) {
        return;
    }
}

From source file:de.tor.tribes.util.AttackToTextWriter.java

private static boolean writeBlocksToFiles(List<String> pBlocks, Tribe pTribe, File pPath) {
    int fileNo = 1;
    String baseFilename = pTribe.getName().replaceAll("\\W+", "");
    for (String block : pBlocks) {
        String fileName = FilenameUtils.concat(pPath.getPath(), baseFilename + fileNo + ".txt");
        FileWriter w = null;
        try {/*from   ww  w  .j  a  v a 2  s  .  com*/
            w = new FileWriter(fileName);
            w.write(block);
            w.flush();
            w.close();
        } catch (IOException ioe) {
            logger.error("Failed to write attack to textfile", ioe);
            return false;
        } finally {
            if (w != null) {
                try {
                    w.close();
                } catch (IOException ignored) {
                }
            }
        }
        fileNo++;
    }
    return true;
}

From source file:com.rpgsheet.xcom.PimpMyXcom.java

public static void saveApplicationProperties(Properties appProperties) throws IOException {
    String homePath = System.getProperty(SYSTEM_PROPERTY_USER_HOME);
    File appPropertiesFile = new File(homePath, APPLICATION_PROPERTIES_FILE);
    FileWriter fileWriter = new FileWriter(appPropertiesFile);
    appProperties.store(fileWriter, APPLICATION_COMMENT);
    fileWriter.close();
}

From source file:jlite.cli.JobSubmit.java

private static void run(String jdlFile, CommandLine line) throws Exception {
    if (line.hasOption("debug")) {
        Logger logger = Logger.getLogger(GridSessionImpl.class);
        logger.setLevel(Level.DEBUG);
    }//from   w  w  w.  j a  v  a  2 s . com

    GridSessionConfig conf = new GridSessionConfig();
    GridSession grid;

    if (line.hasOption("proxypath")) {
        conf.setProxyPath(line.getOptionValue("proxypath"));
    }

    String vo = Util.readVOFromVOMSProxy(conf.getProxyPath());

    if (line.hasOption("xml")) {
        System.out.println("<vo>" + vo + "</vo>");
    } else {
        System.out.println("Working VO: " + vo);
    }
    String wmProxyURL = conf.getWMProxies().get(vo);
    if (line.hasOption("e")) {
        wmProxyURL = line.getOptionValue("e");
    }
    if (wmProxyURL == null) {
        throw new GridAPIException("Could not find WMProxy server for VO: " + vo);
    }
    if (line.hasOption("xml")) {
        System.out.println("<wmProxy>" + wmProxyURL + "</wmProxy>");
    } else {
        System.out.println("Connecting to WMProxy service: " + wmProxyURL + "\n");
    }

    String delegationId;
    if (line.hasOption("a")) {
        grid = GridSessionFactory.create(conf);
        delegationId = line.getOptionValue("d", System.getProperty("user.name"));
        grid.delegateProxy(wmProxyURL, delegationId);
        if (line.hasOption("xml")) {
            System.out.println("<delegationId>" + delegationId + "</delegationId>");
        } else {
            System.out.println("Your proxy has been successfully delegated to WMProxy\n"
                    + "Delegation identifier: " + delegationId + "\n");
        }
    } else {
        delegationId = line.getOptionValue("d", System.getProperty("user.name"));
        conf.setDelegationId(delegationId);
        grid = GridSessionFactory.create(conf);
    }

    JobAd jad = new JobAd();
    jad.fromFile(jdlFile);
    if (line.hasOption("r")) {
        Op expr = new Op(Expr.EQUAL, Constant.getInstance("other.GlueCEUniqueID"),
                Constant.getInstance(line.getOptionValue("r")));
        jad.delAttribute("Requirements");
        jad.setAttribute("Requirements", expr);
    }

    String inputDir = line.getOptionValue("in", System.getProperty("user.dir"));

    String jobId = grid.submitJob(wmProxyURL, jad.toString(), inputDir);

    if (line.hasOption("xml")) {
        System.out.println("<jobId>" + jobId + "</jobId>");
    } else {
        System.out.println("The job has been successfully submitted to the WMProxy");
        System.out.println("Your job identifier is: \n\n\t" + jobId);
    }

    if (line.hasOption("o")) {
        File outFile = new File(line.getOptionValue("o"));
        FileWriter out = new FileWriter(outFile, true);
        out.write(jobId + "\n");
        out.close();
        if (line.hasOption("xml")) {
            System.out.println("<jodIdFile>" + outFile.getAbsolutePath() + "</jobIdFile>");
        } else {
            System.out.println(
                    "\nThe job identifier has been saved in the following file:\n" + outFile.getAbsolutePath());
        }
    }
}

From source file:gov.nasa.ensemble.dictionary.nddl.ModelGenerator.java

private static StringBuilder readModelFile(File file) throws IOException {
    StringBuilder result = new StringBuilder();
    FileInputStream fis = null;//from   ww  w  . j a  v  a 2  s.co  m
    InputStreamReader reader = null;
    int size;
    try {
        char[] buffer = new char[1024];
        fis = new FileInputStream(file);

        FileWriter filewriter = new FileWriter("out");
        String encname = filewriter.getEncoding();
        filewriter.close();

        Charset cs = Charset.forName(encname);
        CharsetDecoder csd = cs.newDecoder();
        csd.onMalformedInput(CodingErrorAction.REPLACE);

        reader = new InputStreamReader(fis, csd);
        while ((size = reader.read(buffer, 0, 1024)) > 0) {
            result.append(buffer, 0, size);
        }
    } catch (Exception e) {
        // System.out.println(encoding);
        e.printStackTrace();
    } finally {
        if (fis != null) {
            fis.close();
        }

        if (reader != null) {
            reader.close();
        }
    }

    return result;
}

From source file:com.avatarproject.core.storage.UserCache.java

/**
 * Adds a player into the custom UserCache.
 * @param player Player to add to the cache.
 *///from  w ww.j a  v a  2s .  c  o  m
@SuppressWarnings("unchecked")
public static void addUser(Player player) {
    String name = player.getName();
    UUID uuid = player.getUniqueId();
    JSONArray array = getUserCache();
    try {
        for (int n = 0; n < array.size(); n++) { //Loop through all the objects in the array.
            JSONObject object = (JSONObject) array.get(n);
            if (object.get("id").equals(uuid.toString())) { //Check if the player's UUID exists in the cache.
                if (String.valueOf(object.get("name")).equalsIgnoreCase(name)) {
                    return;
                } else {
                    object.put("name", name); //Update the user.
                    FileWriter fileOut = new FileWriter(usercache);
                    fileOut.write(array.toJSONString()); //Write the JSON array to the file.
                    fileOut.close();
                    return;
                }
            }
        }
        JSONObject newEntry = new JSONObject();
        newEntry.put("id", uuid.toString());
        newEntry.put("name", name);
        array.add(newEntry); //Add a new player into the cache.
        FileWriter fileOut = new FileWriter(usercache);
        fileOut.write(array.toJSONString()); //Write the JSON array to the file.
        fileOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.web4thejob.util.L10nUtil.java

public static void logMissingMessage(String code, String defaultValue) {
    File file = new File(System.getProperty("user.home"),
            "w4tj_" + CoreUtil.getUserLocale().toString() + ".log");
    FileWriter out;
    try {/*from  w w  w.  j ava2 s  .c  om*/
        out = new FileWriter(file, true);
        out.write(code + "=" + defaultValue + System.getProperty("line.separator"));
        out.close();
        // logger.warn("Missiing message: " + code + "=" + defaultValue);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.yahoo.storm.yarn.StormMasterCommand.java

public static void downloadStormYaml(StormMaster.Client client, String storm_yaml_output) {
    String conf_str = "Not Avaialble";

    //fetch storm.yaml from Master
    try {/*from  w  w w . j  av  a2 s.  c  o  m*/
        conf_str = client.getStormConf();
    } catch (TTransportException ex) {
        LOG.error("Exception in downloading storm.yaml", ex);
    } catch (TException ex) {
        LOG.error("Exception in downloading storm.yaml", ex);
    }

    //storm the fetched storm.yaml into storm_yaml_output or stdout
    try {
        Object json = JSONValue.parse(conf_str);
        Map<?, ?> conf = (Map<?, ?>) json;
        Yaml yaml = new Yaml();

        if (storm_yaml_output == null) {
            LOG.info("storm.yaml downloaded:");
            System.out.println(yaml.dump(conf));
        } else {
            FileWriter out = new FileWriter(storm_yaml_output);
            yaml.dump(conf, out);
            out.flush();
            out.close();
            LOG.info("storm.yaml downloaded into " + storm_yaml_output);
        }
    } catch (Exception ex) {
        LOG.error("Exception in storing storm.yaml. ", ex);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.util.SaveModelUtils.java

public static void writeModelParameters(TaskContext aContext, File aOutputFolder, List<String> aFeatureSet,
        List<Object> aFeatureParameters) throws Exception {
    // write meta collector data
    // automatically determine the required metaCollector classes from the
    // provided feature
    // extractors
    Set<Class<? extends MetaCollector>> metaCollectorClasses;
    try {//from ww  w.  j  a v  a2  s .c o m
        metaCollectorClasses = TaskUtils.getMetaCollectorsFromFeatureExtractors(aFeatureSet);
    } catch (ClassNotFoundException e) {
        throw new ResourceInitializationException(e);
    } catch (InstantiationException e) {
        throw new ResourceInitializationException(e);
    } catch (IllegalAccessException e) {
        throw new ResourceInitializationException(e);
    }

    // collect parameter/key pairs that need to be set
    Map<String, String> metaParameterKeyPairs = new HashMap<String, String>();
    for (Class<? extends MetaCollector> metaCollectorClass : metaCollectorClasses) {
        try {
            metaParameterKeyPairs.putAll(metaCollectorClass.newInstance().getParameterKeyPairs());
        } catch (InstantiationException e) {
            throw new ResourceInitializationException(e);
        } catch (IllegalAccessException e) {
            throw new ResourceInitializationException(e);
        }
    }

    Properties parameterProperties = new Properties();
    for (Entry<String, String> entry : metaParameterKeyPairs.entrySet()) {
        File file = new File(aContext.getStorageLocation(META_KEY, AccessMode.READWRITE), entry.getValue());

        String name = file.getName();
        String subFolder = aOutputFolder.getAbsoluteFile() + "/" + name;
        File targetFolder = new File(subFolder);
        copyToTargetLocation(file, targetFolder);
        parameterProperties.put(entry.getKey(), name);

        // should never be reached
    }

    for (int i = 0; i < aFeatureParameters.size(); i = i + 2) {

        String key = (String) aFeatureParameters.get(i).toString();
        String value = aFeatureParameters.get(i + 1).toString();

        if (valueExistAsFileOrFolderInTheFileSystem(value)) {
            String name = new File(value).getName();
            String destination = aOutputFolder + "/" + name;
            copyToTargetLocation(new File(value), new File(destination));
            parameterProperties.put(key, name);
            continue;
        }
        parameterProperties.put(key, value);
    }

    FileWriter writer = new FileWriter(new File(aOutputFolder, MODEL_PARAMETERS));
    parameterProperties.store(writer, "");
    writer.close();
}

From source file:com.thruzero.common.core.utils.FileUtilsExt.java

/**
 * Append the given {@code data} to the specified {@code file}.
 *//*from w w w  .  j  av a  2 s.  com*/
public static void appendToFile(final File file, final String data) throws IOException {
    FileWriter fw = new FileWriter(file, true);
    fw.write(data);
    fw.close();
}